
--------------------------------------------------Tej 01062023
-- SEQUENCE: public.ChargeTypes_ChargeId_seq

-- DROP SEQUENCE IF EXISTS public."ChargeTypes_ChargeId_seq";

CREATE SEQUENCE IF NOT EXISTS public."DoctorAppointmentNotice_DoctorAppointmentNoticeId_seq"
    INCREMENT 1
    START 1
    MINVALUE 1
    MAXVALUE 9223372036854775807
    CACHE 1;

ALTER SEQUENCE public."DoctorAppointmentNotice_DoctorAppointmentNoticeId_seq"
    OWNER TO postgres;

--------------------


-- Table: public.DoctorAppointmentNotice

-- DROP TABLE IF EXISTS public."DoctorAppointmentNotice";

CREATE TABLE IF NOT EXISTS public."DoctorAppointmentNotice"
(
    "DoctorAppointmentNoticeId" integer NOT NULL DEFAULT nextval('"DoctorAppointmentNotice_DoctorAppointmentNoticeId_seq"'::regclass),
    "LocationId" integer,
    "ProviderId" integer,
    "FromDate" timestamp(6) without time zone,
    "ToDate" timestamp(6) without time zone,
    "Description" character varying(500) COLLATE pg_catalog."default",
    "Active" boolean NOT NULL,
    "CreatedBy" integer NOT NULL,
    "CreatedDate" timestamp(6) without time zone,
    "ModifiedBy" integer,
    "ModifiedDate" timestamp(6) without time zone,
    CONSTRAINT "DoctorAppointmentNoticeId_pkey" PRIMARY KEY ("DoctorAppointmentNoticeId"),
    CONSTRAINT "FK_DoctorAppointmentNotice_CreatedBy" FOREIGN KEY ("CreatedBy")
        REFERENCES public."Account" ("AccountId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE CASCADE,
    CONSTRAINT "FK_DoctorAppointmentNotice_LocationId" FOREIGN KEY ("LocationId")
        REFERENCES public."Location" ("LocationId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE CASCADE,
    CONSTRAINT "FK_DoctorAppointmentNotice_ModifiedBy" FOREIGN KEY ("ModifiedBy")
        REFERENCES public."Account" ("AccountId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE CASCADE,
    CONSTRAINT "FK_DoctorAppointmentNotice_ProviderId" FOREIGN KEY ("ProviderId")
        REFERENCES public."Provider" ("ProviderId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE CASCADE
)

TABLESPACE pg_default;

ALTER TABLE IF EXISTS public."DoctorAppointmentNotice"
    OWNER to postgres;
	

alter table IF  EXISTS "ScanMachineAvailability" 
add column IF NOT EXISTS "ScanWeekId" integer;


	
alter table IF  EXISTS "ScanMachineAvailability" 
add column IF NOT EXISTS "AvailableDate" text;
-------------------------------------------Manish 01062023
create table IF NOT EXISTS public."PharmacyDepartmentIndentHeader"(
			"PharmacyDepartmentIndentHeaderId" bigserial primary key,
			"RequiredDate" date,
			"CreatedBy" int references "Account"("AccountId"),
			"CreatedDate" timestamp without time zone,
			"Active" boolean default true,
			"PharmacyDepartmentId" int references "PharmacyDepartment"("PharmacyDepartmentId"),
			"ApprovedWareHouseId" int references "PharmacyWareHouse"("PharmacyWareHouseId"),
			"ApprovedRetailStoreId" int references "RetailPharmacy"("RetailPharmacyId"),
			"Reason" text
);

create table IF NOT EXISTS public."PharmacyDepartmentIndentDetail"(
	"PharmacyDepartmentIndentDetailId" bigserial primary key,
	"PharmacyDepartmentIndentHeaderId" bigint references "PharmacyDepartmentIndentHeader"("PharmacyDepartmentIndentHeaderId"),
	"PharmacyProductId" int references "PharmacyProduct"("PharmacyProductId"),
	"IsReplaced" boolean default false,
	"RequestedQuantity" int not null	
);

-----------------------

create table IF NOT EXISTS public."GeneralNotification" (
		"GeneralNotificationId" bigserial primary key,
		"Message" text,
		"CreatedDate" timestamp without time zone,
		"IsPriority" boolean default false,
		"CreatedBy" int references "Account"("AccountId"),
		"ModulesMasterId" int references "ModulesMaster"("ModulesMasterId"),
		"RedirectUrl" text,
		"ForRoles" text,
		"ForAccounts" text,
		"IsRead" boolean default false,
		"WebNotificationLogTypeId" int references "WebNotificationLogType"("WebNotificationLogTypeId"),
		"ReferenceId" bigint
);
----------------
create table IF NOT EXISTS public."PharmacyDepartmentIssueHeader"(
		"PharmacyDepartmentIssueHeaderId" bigserial primary key,
		"PharmacyDepartmentIndentHeaderId" bigint references "PharmacyDepartmentIndentHeader"("PharmacyDepartmentIndentHeaderId"),
		"Comment" text,
		"CreatedBy" int references "Account"("AccountId"),
		"CreatedDate" timestamp without time zone
);

create table IF NOT EXISTS public."PharmacyDepartmentIssueDetail"(
		"PharmacyDepartmentIssueDetailId" bigserial primary key,
		"PharmacyDepartmentIssueHeaderId" bigint references "PharmacyDepartmentIssueHeader"("PharmacyDepartmentIssueHeaderId"),
		"PharmacyDepartmentIndentDetailId"  bigint references "PharmacyDepartmentIndentDetail"("PharmacyDepartmentIndentDetailId"),
		"PharmacyProductId" int references "PharmacyProduct"("PharmacyProductId"),
		"PharmacyRetailStockId" int references "PharmacyRetailStock"("PharmacyRetailStockId" ),
		"ApprovedQuantity" int
);

-------------------------------------------------02june2023 Jayshree
drop function IF EXISTS  "Masterbills_AppointmentReports"(date,date,integer);
CREATE OR REPLACE FUNCTION public."Masterbills_AppointmentReports"(
	"fromDate" date DEFAULT NULL::date,
	"toDate" date DEFAULT NULL::date,	
	locationid integer DEFAULT NULL::integer)
    RETURNS TABLE("TotalItems" bigint,  "BillNumber" character varying,
				  "BillDate" timestamp without time zone, "BillStatusTypeId" integer,"BillStatus" character varying,
				  "Total" numeric,"Discount" numeric,"NetTotal" numeric,							
				  "Receipts" text,"Receipts_Cost" text,"ReceiptSum" numeric,"PatientName" text, "Mobile" character varying,
				  "UMRNo" character varying, "LocationId" integer,"ModuleName" character varying,"AppointmentNo" character varying,
				 "AppointmentDate" date) 
	LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000

AS $BODY$
begin
return query

with getreceipts as (
	select  MB."MasterBillId",MB."BillNumber",string_agg(R."ReceiptId"::text,',')   AS "Receipts",
string_agg(R."Cost"::text,',')  AS "Receipts_Cost",
	sum(R."Cost") as "ReceiptSum"
	from "MasterBill" MB 
	 join  "Receipt" R on R."MasterBillId"=MB."MasterBillId"	
	group by (MB."MasterBillId")
	order by MB."MasterBillId" asc

)
 -- select * from "Appointment"
select 
COUNT(*) OVER () AS "TotalItems",MB."BillNumber",MB."BillDate",MB."BillStatusTypeId",BST."Name" as "BillStatus",
MB."Total",MB."Discount",MB."NetTotal",GR."Receipts",GR."Receipts_Cost",GR."ReceiptSum",
P."FullName" as "PatientName",P."Mobile",P."UMRNo",A."LocationId",MM."ModuleName",
A."AppointmentNo",A."AppointmentDate"
FROM "MasterBill" MB
 Join "Appointment" A on A."AppointmentId"=MB."ModuleId"
 join "BillStatusType" BST on BST."BillStatusTypeId"=MB."BillStatusTypeId"
 join "Patient" P on P."PatientId"=MB."PatientId"
 join "ModulesMaster" MM on MM."ModulesMasterId"=MB."ModulesMasterId"
 join "getreceipts" GR on GR."MasterBillId"=MB."MasterBillId"
where  
A."AppointmentDate"::date=now()::date;

end
$BODY$;
----------------------------------------------------------------------------05June2023 Sravani
alter table IF EXISTS "BookScanAppointment" 
add column If not exists "DiscountPercentage" integer, 
add column If not exists"DiscountAmount" numeric,
add column  If not exists"AuthorityId" integer, 
add column If not exists "ReasonId" integer;


alter table IF EXISTS "BookScanAppointment" 
DROP CONSTRAINT IF EXISTS "FK_BookScanAppointment_AuthorityId";
alter table IF EXISTS "BookScanAppointment" 
ADD CONSTRAINT "FK_BookScanAppointment_AuthorityId" FOREIGN KEY ("AuthorityId")
        REFERENCES "AuthorityMaster" ("AuthorityMasterId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION;

		
alter table IF EXISTS "BookScanAppointment" 
DROP CONSTRAINT IF EXISTS "BookScanAppointment_ReasonId";
alter table IF EXISTS "BookScanAppointment" 
ADD CONSTRAINT  "BookScanAppointment_ReasonId" FOREIGN KEY ("ReasonId")
        REFERENCES "Reasons" ("ReasonsId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION;

-------------------------------------------------------------------------06June2023 Kalyan
alter table IF EXISTS "LabMainDetail" 
add column If not exists "ConsentFormRequired" BOOLEAN  default false, 
add column If not exists "AssignDoctorRequired" BOOLEAN  default false;

-------------------------------------------------------------------------06June2023 Chandana
alter table IF EXISTS "GynEncounter"
add column If not exists "PatientId" integer,
DROP CONSTRAINT IF EXISTS "GynEncounter_PatientId_fkey",
add CONSTRAINT "GynEncounter_PatientId_fkey" FOREIGN KEY ("PatientId")
 REFERENCES public."Patient" ("PatientId") MATCH SIMPLE
 ON UPDATE NO ACTION
 ON DELETE NO ACTION;

-------------------------------------------------------------------------07June2023 Mounika A
alter table If Exists "PediatricEncounter"
add column  If not Exists "Allergies" text;

DO $$                  
    BEGIN 
        IF EXISTS
            ( SELECT 1
              FROM   information_schema.tables 
              WHERE  table_schema = 'public'
              AND    table_name = 'Menu'
            )
        THEN
            UPDATE "Menu"
            SET "EncounterKey" = 'allergies'
            where "Url" ilike '%/app/pediatric-encounter/:id/:type/obAllergies%';
        END IF ;
    END
   $$ ;

-------------------------------------------------------------------------08June2023 Srilekha
CREATE SEQUENCE IF NOT EXISTS public."PaymentType_Seq";
CREATE TABLE IF NOT EXISTS public."PaymentType"
(
    "PaymentTypeId" integer NOT NULL DEFAULT nextval('"PaymentType_Seq"'::regclass),
    "PaymentTypeName" character varying(255) COLLATE pg_catalog."default",
    "Description" character varying(150) COLLATE pg_catalog."default",
    "IsActive" boolean DEFAULT true,
    "PaymentTypeValue" character(1) COLLATE pg_catalog."default" NOT NULL,    
    CONSTRAINT "PaymentType_pkey" PRIMARY KEY ("PaymentTypeId")
);
-----------------------------------------------------------------
INSERT INTO public."PaymentType"("PaymentTypeId", "PaymentTypeName", "Description", "IsActive", "PaymentTypeValue")
SELECT 1,'Full Payment','Full Payment is the payment type',true,'F'
WHERE
NOT EXISTS (
SELECT "PaymentTypeId" FROM public."PaymentType" WHERE "PaymentTypeId" = 1
);

INSERT INTO public."PaymentType"("PaymentTypeId", "PaymentTypeName", "Description", "IsActive", "PaymentTypeValue")
SELECT 2,'Partial Payment','Partial Payment is the payment type',true,'P'
WHERE
NOT EXISTS (
SELECT "PaymentTypeId" FROM public."PaymentType" WHERE "PaymentTypeId" = 2
);
----------------------------------------------------------------
ALTER TABLE IF EXISTS "Appointment"
DROP COLUMN IF EXISTS "PaymentType"; 
ALTER TABLE IF EXISTS "Appointment"
ADD COLUMN IF NOT EXISTS "PaymentType" character(1) DEFAULT 'F'::bpchar;

-------------------------------------------------------------09June2023 Sravani
CREATE SEQUENCE  IF NOT EXISTS "ScanLogType_ScanLogTypeId_seq"
    INCREMENT 1
    START 1
    MINVALUE 1
    MAXVALUE 9223372036854775807
    CACHE 1;


CREATE TABLE IF NOT EXISTS "ScanLogType"
(
    "ScanLogTypeId" integer NOT NULL DEFAULT nextval('"ScanLogType_ScanLogTypeId_seq"'::regclass),
    "LogTypeName" character varying(50) COLLATE pg_catalog."default" NOT NULL,
    "Active" boolean NOT NULL DEFAULT true,
    CONSTRAINT "ScanLogType_pkey" PRIMARY KEY ("ScanLogTypeId"),
    CONSTRAINT "UQ_ScanLogType_LogTypeName" UNIQUE ("LogTypeName")
);

INSERT INTO public."ScanLogType"("LogTypeName","Active")
SELECT 'ScanSubClassification', true
WHERE
NOT EXISTS (
SELECT "LogTypeName" FROM public."ScanLogType" WHERE "LogTypeName" = 'ScanSubClassification'
);

INSERT INTO public."ScanLogType"("LogTypeName","Active")
SELECT 'ScanAppointmentNotice', true
WHERE
NOT EXISTS (
SELECT "LogTypeName" FROM public."ScanLogType" WHERE "LogTypeName" = 'ScanAppointmentNotice'
);
INSERT INTO public."ScanLogType"("LogTypeName","Active")
SELECT 'ScanTestMaster', true
WHERE
NOT EXISTS (
SELECT "LogTypeName" FROM public."ScanLogType" WHERE "LogTypeName" = 'ScanTestMaster'
);
INSERT INTO public."ScanLogType"("LogTypeName","Active")
SELECT 'ScanMachineMaster', true
WHERE
NOT EXISTS (
SELECT "LogTypeName" FROM public."ScanLogType" WHERE "LogTypeName" = 'ScanMachineMaster'
);
INSERT INTO public."ScanLogType"("LogTypeName","Active")
SELECT 'BookScanAppointment', true
WHERE
NOT EXISTS (
SELECT "LogTypeName" FROM public."ScanLogType" WHERE "LogTypeName" = 'BookScanAppointment'
);
INSERT INTO public."ScanLogType"("LogTypeName","Active")
SELECT 'ScanMachineAvailability', true
WHERE
NOT EXISTS (
SELECT "LogTypeName" FROM public."ScanLogType" WHERE "LogTypeName" = 'ScanMachineAvailability'
);

CREATE SEQUENCE IF NOT EXISTS "ScanLogType_ScanLogTypeId_seq1"
    INCREMENT 1
    START 1
    MINVALUE 1
    MAXVALUE 9223372036854775807
    CACHE 1;

	
CREATE TABLE IF NOT EXISTS "ScanLog"
(
    "ScanLogId" integer NOT NULL DEFAULT nextval('"ScanLogType_ScanLogTypeId_seq1"'::regclass),
    "ScanLogTypeId" integer NOT NULL,
    "LogFrom" smallint NOT NULL,
    "LogDate" timestamp(6) without time zone NOT NULL,
    "AccountId" integer,
    "LogDescription" text COLLATE pg_catalog."default" NOT NULL,
    "LocationId" integer,
    CONSTRAINT "ScanLog_pkey" PRIMARY KEY ("ScanLogId"),
    CONSTRAINT "FK_ScanLog_ScanLogTypeId" FOREIGN KEY ("ScanLogTypeId")
        REFERENCES "ScanLogType" ("ScanLogTypeId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE CASCADE,
    CONSTRAINT "ScanLog_LocationId_fkey" FOREIGN KEY ("LocationId")
        REFERENCES "Location" ("LocationId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION
);
---------------------------------------------------------------12June2023 Srilekha

ALTER TABLE "Appointment" ALTER COLUMN "PaymentType" DROP DEFAULT; 

---------------------------------------------------------------12June2023 Tej
DROP FUNCTION IF EXISTS public."collection_userLogin"(date, date, integer, integer);
-- FUNCTION: public.collection_userLogin(date, date, integer, integer)

-- DROP FUNCTION IF EXISTS public."collection_userLogin"(date, date, integer, integer);

CREATE OR REPLACE FUNCTION public."collection_userLogin"(
	"fromDate" date DEFAULT NULL::date,
	"toDate" date DEFAULT NULL::date,
	accountid integer DEFAULT NULL::integer,
	locationid integer DEFAULT NULL::integer)
    RETURNS TABLE("AccountId" integer, "ReceiptCreatedBy" text, "RoleName" character varying, "ReceiptDate" timestamp without time zone, "ReceiptId" integer, "ReceiptTypeId" integer, "AreaType" character varying, "RefId" character varying, "PayTypeName" character varying, "PaymentDetails" character varying, "PaidAmount" numeric, "PatientName" text, "UMRNo" character varying, "Mobile" character varying) 
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000

AS $BODY$
begin
return query

with accountdata as (
select a."AccountId",a."FullName" "EmployeeName",rol."RoleName"
from "Account" a
JOIN "LocationAccountMap" LAM on LAM."AccountId"=a."AccountId"  
join "Role" rol on rol."RoleId" = a."RoleId" and lower(rol."RoleName") <> lower('Patient')
where a."RoleId"<>4  --and a."AccountId"=6776 and LAM."LocationId"=2
 and	case when accountid is null then 1=1 else a."AccountId"=accountid end   
AND CASE WHEN (locationid IS NULL OR locationid=0) THEN 1=1 ELSE LAM."LocationId"=locationid END
)
, appointment as (

select R."ReceiptId",A."FullName" "ReceiptCreatedBy",Rl."RoleName",R."CreatedDate" "ReceiptDate",R."CreatedBy",RT."Name" as "AreaType"
, coalesce(case when R."ReceiptTypeId"=1 then R."Cost" end,0) as "PaidAmount" ,
	coalesce(case when R."ReceiptTypeId"=2 then R."Cost" end,0) as "RefundAmount" ,
	--R."Cost"  as "PaidAmount" ,
	R."ReceiptTypeId"
 ,Ad."FollowUpForAppointmentId",
	Ad."AppointmentDate",Ad."AppointmentNo", Ad."AppointmentTime",Ad."LocationId",
pa."FullName" "PatientName",Pa."UMRNo",pa."Mobile",pr."FullName" as "ProviderName",Ad."PaymentType",
pt."PayTypeName",  CASE
    WHEN R."PaymentDetails" = 'null' THEN null
    ELSE R."PaymentDetails"
  END AS "PaymentDetails" , R."AppointmentId",R."IsAppointmentReceipt" 
	from "Receipt" R
join "Appointment" Ad on Ad."AppointmentId"=R."RespectiveId" 
join "Provider" pr on pr."ProviderId"= ad."ProviderId"
join "Patient" pa on Ad."PatientId"=pa."PatientId"
join "Account" A on A."AccountId"=R."CreatedBy"
join "Role" Rl on Rl."RoleId"=A."RoleId"
join "PayType" pt on pt."PayTypeId"=R."PayTypeId"
join "ReceiptAreaType" RT on R."ReceiptAreaTypeId"=RT."ReceiptAreaTypeId"
	where  R."Active" <> false  and R."ReceiptAreaTypeId" in (4,5) and
	--R."CreatedBy" =6776 and Ad."LocationId" = 2
--and R."CreatedDate"::date ='2023-04-18'
 case when "accountid" is null then 1=1 else  R."CreatedBy"  = "accountid" end  
 and case when "locationid" is null then 1=1 else Ad."LocationId" = "locationid" end

 	and case when "fromDate" is null then 1=1 else "fromDate"<= R."CreatedDate"::date end 
 		and case when "toDate" is null then 1=1 else R."CreatedDate"::date<=  "toDate" end 
	
 
)
,patient as(			
						select 
                               coalesce(case when R."ReceiptTypeId"=1 then R."Cost" end,0) as "PaidAmount" ,
	coalesce(case when R."ReceiptTypeId"=2 then R."Cost" end,0) as "RefundAmount" ,
	
                                A."FullName" as "ReceiptCreatedBy",Rl."RoleName",
                                P."FullName" as "PatientName",P."FirstName",P."MiddleName",P."LastName",
                                P."Age",P."Gender",P."UMRNo",P."Mobile",P."DateOfBirth",
                                R."ReceiptId",R."CreatedBy",RT."Name" as "AreaType",P."PatientId",
				                PT."PayTypeName",R."PaymentDetails",R."CreatedDate" "ReceiptDate"	,R."ReceiptTypeId"
	                            FROM "Receipt" R
	                            join "Patient" P on P."PatientId" = R."RespectiveId"  
								join  "Account" PA on PA."ReferenceId"=P."PatientId"
								JOIN "LocationAccountMap" LAM on LAM."AccountId"=PA."AccountId"  
	                            join "Account" A on A."AccountId" = R."CreatedBy"
						        join "Role" Rl on Rl."RoleId"=A."RoleId"
	                            join "PayType" PT on PT."PayTypeId" = R."PayTypeId"
							join "ReceiptAreaType" RT on R."ReceiptAreaTypeId"=RT."ReceiptAreaTypeId"
								where  R."ReceiptAreaTypeId" in (3,6)
--	and LAM."LocationId"=2 and R."CreatedDate"::date='2023-04-14 and R."CreatedBy"=6776
									
 	and case when "fromDate" is null then 1=1 else "fromDate"<= R."CreatedDate"::date end and
 	case when "toDate" is null then 1=1 else R."CreatedDate"::date<=  "toDate" end and
	case when "locationid" is null then 1=1 else  LAM."LocationId" = "locationid"::int end and
	case when "accountid" is null then 1=1 else R."CreatedBy"="accountid" end 
	
)

,admission as (
	
select R."ReceiptId",Rl."RoleName",R."CreatedDate" "ReceiptDate",
A."FullName" "ReceiptCreatedBy" ,pt."PayTypeName",R."PaymentDetails"
,R."CreatedBy",RT."Name" as "AreaType",R."ReceiptTypeId",
-- R."Cost"  as "PaidAmount" 
	coalesce(case when R."ReceiptTypeId"=1 then R."Cost" end,0) as "PaidAmount" ,
	coalesce(case when R."ReceiptTypeId"=2 then R."Cost" end,0) as "RefundAmount" 
 ,Ad."AdmissionNo",ad."AdmissionDate",	
pa."FullName" "PatientName",pa."UMRNo",pa."Mobile",pr."FullName" as "ProviderName"

	from "Receipt" R
join "Admission" ad on Ad."AdmissionId"=R."RespectiveId" and ad."Active" is not false
join "Provider" pr on pr."ProviderId"= ad."ProviderId"
join "Patient" pa on Ad."PatientId"=pa."PatientId"
join "Account" A on A."AccountId"=R."CreatedBy"
join "Role" Rl on Rl."RoleId"=A."RoleId"
join "PayType" pt on pt."PayTypeId"=R."PayTypeId"
	join "ReceiptAreaType" RT on R."ReceiptAreaTypeId"=RT."ReceiptAreaTypeId"
	where R."Active" is not false and R."ReceiptAreaTypeId" in (12,13) and
	--and  Ad."LocationId"=2 and  R."CreatedBy"=6776
case when "accountid" is null then 1=1 else  R."CreatedBy"  = "accountid" end 
and case when "locationid" is null then 1=1 else Ad."LocationId" = "locationid" end 
and case when "fromDate" is null then 1=1 else "fromDate"<= R."CreatedDate"::date end 
 		and case when "toDate" is null then 1=1 else R."CreatedDate"::date<=  "toDate" end  

)
,lab as (
-- 	select 
--  R."Cost" as "PaidAmount",PT."PayTypeName",R."PaymentDetails", 
-- 	 AR."FullName" "ReceiptCreatedBy",Rl."RoleName",R."CreatedBy",
-- 	 nlbh."RequisitionNumber",	
-- 	 nlbh."PatientId", nlbh."DoctorId",
-- 	COALESCE (nlbh."PatientName" ,p."FullName" ) as "PatientName",COALESCE (p."Mobile" ,nlbh."Mobile" ) as "Mobile", p."UMRNo",           
--       R."ReceiptId",RT."Name" as "AreaType",R."CreatedDate" "ReceiptDate"	,R."ReceiptTypeId"

SELECT 
	coalesce(case when R."ReceiptTypeId"=1 then R."Cost" end,0) as "PaidAmount" ,
	coalesce(case when R."ReceiptTypeId"=2 then R."Cost" end,0) as "RefundAmount" ,
	-- R."Cost" as "PaidAmount",
	PT."PayTypeName", CASE
    WHEN R."PaymentDetails" = 'null' THEN null
    ELSE R."PaymentDetails"
  END AS "PaymentDetails" , 
	 AR."FullName" "ReceiptCreatedBy",Rl."RoleName",R."CreatedBy",
	 nlbh."RequisitionNumber",	
	 nlbh."PatientId", nlbh."DoctorId",
	COALESCE (nlbh."PatientName" ,p."FullName" ) as "PatientName",COALESCE (p."Mobile" ,nlbh."Mobile" ) as "Mobile", p."UMRNo",           
      R."ReceiptId",RT."Name" as "AreaType" ,R."CreatedDate" "ReceiptDate"	,R."ReceiptTypeId"
			 from "Receipt" R
			join "NewLabBookingHeader" nlbh on nlbh."NewLabBookingHeaderId"=R."RespectiveId"                                
			join "PayType" pt ON PT."PayTypeId" = nlbh."PayTypeId"                                                                      
			left join "Patient" p ON p."PatientId" =nlbh."PatientId"
			left join "Provider" prv on prv."ProviderId" = nlbh."DoctorId"                                
			left join "Account" e on e."AccountId" = nlbh."EmployeeId" 
			left join "Account" AR on AR."AccountId" = R."CreatedBy"
			join "Role" Rl on Rl."RoleId"=AR."RoleId"
			join "ReceiptAreaType" RT on R."ReceiptAreaTypeId"=RT."ReceiptAreaTypeId"
		where R."ReceiptAreaTypeId" = 8
		--and nlbh."LocationId"=2 and R."CreatedDate"::date='2023-04-18'
 	and case when "fromDate" is null then 1=1 else "fromDate"<= R."CreatedDate"::date end and
	case when "toDate" is null then 1=1 else R."CreatedDate"::date<=  "toDate" end and
 	case when "locationid" is null then 1=1 else  nlbh."LocationId" = "locationid"::int end and
	case when "accountid" is null then 1=1 else nlbh."CreatedBy"="accountid" end 

UNION
		
SELECT 
	coalesce(case when R."ReceiptTypeId"=1 then R."Cost" end,0) as "PaidAmount" ,
	coalesce(case when R."ReceiptTypeId"=2 then R."Cost" end,0) as "RefundAmount" ,
	-- R."Cost" as "PaidAmount", 
	PT."PayTypeName",R."PaymentDetails",
	 AR."FullName" "ReceiptCreatedBy" ,Rl."RoleName",R."CreatedBy",
	 nlbh."RequisitionNumber",
	 nlbh."PatientId", nlbh."DoctorId", 
	COALESCE (nlbh."PatientName" ,p."FullName" ) as "PatientName",COALESCE (p."Mobile" ,nlbh."Mobile" ) as "Mobile", p."UMRNo",           
      R."ReceiptId",RT."Name" as "AreaType",R."CreatedDate" "ReceiptDate"	,R."ReceiptTypeId"
			
	
		from "NewLabBookingHeader" nlbh
	join "NewLabCancelBookingHeader" SH on SH."NewLabBookingHeaderId"=nlbh."NewLabBookingHeaderId"
	join "Receipt" R on R."RespectiveId"= SH."NewLabCancelBookingHeaderId"	
			join "PayType" pt ON PT."PayTypeId" = nlbh."PayTypeId"                                                                      
			left join "Patient" p ON p."PatientId" =nlbh."PatientId"		
			left join "Account" AR on AR."AccountId" = R."CreatedBy"
			join "Role" Rl on Rl."RoleId"=AR."RoleId"
			join "ReceiptAreaType" RT on R."ReceiptAreaTypeId"=RT."ReceiptAreaTypeId"
		where R."ReceiptAreaTypeId" = 9
		--and nlbh."LocationId"=2 and R."CreatedDate"::date='2023-04-18'
 	and case when "fromDate" is null then 1=1 else "fromDate"<= R."CreatedDate"::date end and
	case when "toDate" is null then 1=1 else R."CreatedDate"::date<=  "toDate" end and
 	case when "locationid" is null then 1=1 else  nlbh."LocationId" = "locationid"::int end and
	case when "accountid" is null then 1=1 else nlbh."CreatedBy"="accountid" end 
		
																		  								   
)

,pharma as (

select 
	coalesce(case when R."ReceiptTypeId"=1 then R."Cost" end,0) as "PaidAmount" ,
	coalesce(case when R."ReceiptTypeId"=2 then R."Cost" end,0) as "RefundAmount" ,
-- R."Cost" as "PaidAmount", 
	PT."PayTypeName",R."PaymentDetails",
	PH."PharmacySaleHeaderId" ,PH."BillNumber",
	A."FullName" "ReceiptCreatedBy",AR."RoleName" ,R."CreatedBy",
	PH."PatientName",PH."Mobile" ,Pa."UMRNo",
	 R."ReceiptId",RT."Name" as "AreaType",R."CreatedDate" "ReceiptDate",R."ReceiptTypeId"
	
	from "Receipt" R
		join "PharmacySaleHeader" PH on PH."PharmacySaleHeaderId"=R."RespectiveId"
		join "Account" A on A."AccountId"=R."CreatedBy"
		join "Role" AR on AR."RoleId"=A."RoleId"
		 join "PayType" PT ON PT."PayTypeId" = R."PayTypeId"  
		join "ReceiptAreaType" RT on R."ReceiptAreaTypeId"=RT."ReceiptAreaTypeId"	 	
		left join "Patient" Pa on Pa."PatientId"::text=PH."PatientId"::text
	where R."ReceiptAreaTypeId"=1  
 		--and  PH."LocationId"=2 and R."CreatedDate"::date='2023-04-18' 	
	 and case when "accountid" is null then 1=1 else R."CreatedBy"="accountid" end and
	
 	case when "fromDate" is null then 1=1 else "fromDate"<= R."CreatedDate"::date end and
 	case when "toDate" is null then 1=1 else R."CreatedDate"::date<=  "toDate" end and
  	case when "locationid" is null then 1=1 else PH."LocationId" = "locationid" end
UNION
	
select 
	coalesce(case when R."ReceiptTypeId"=1 then R."Cost" end,0) as "PaidAmount" ,
	coalesce(case when R."ReceiptTypeId"=2 then R."Cost" end,0) as "RefundAmount" ,
	 --R."Cost" as "PaidAmount", 
	PT."PayTypeName",R."PaymentDetails",
		PH."PharmacySaleHeaderId" ,PH."BillNumber",
		A."FullName" "ReceiptCreatedBy",AR."RoleName" ,R."CreatedBy",
		PH."PatientName",PH."Mobile" ,Pa."UMRNo",
		 R."ReceiptId",RT."Name" as "AreaType",R."CreatedDate" "ReceiptDate",R."ReceiptTypeId"
	from "PharmacySaleHeader" PH 
			join "SaleReturnHeader" SH on SH."PharmacySaleHeaderId"=PH."PharmacySaleHeaderId"
			join "Receipt" R on R."RespectiveId"= SH."SaleReturnHeaderId"
		join "Account" A on A."AccountId"=R."CreatedBy"
		join "Role" AR on AR."RoleId"=A."RoleId"
		 join "PayType" PT ON PT."PayTypeId" = R."PayTypeId"  
		join "ReceiptAreaType" RT on R."ReceiptAreaTypeId"=RT."ReceiptAreaTypeId"	 	
		left join "Patient" Pa on Pa."PatientId"::text=PH."PatientId"::text
	where R."ReceiptAreaTypeId"=7
	
		 and case when "accountid" is null then 1=1 else R."CreatedBy"="accountid" end and
		 case when "fromDate" is null then 1=1 else "fromDate"<= R."CreatedDate"::date end and
		case when "toDate" is null then 1=1 else R."CreatedDate"::date<=  "toDate" end and
		case when "locationid" is null then 1=1 else PH."LocationId" = "locationid" end		
)
,scan as(

select 
	coalesce(case when R."ReceiptTypeId"=1 then R."Cost" end,0) as "PaidAmount" ,
	coalesce(case when R."ReceiptTypeId"=2 then R."Cost" end,0) as "RefundAmount" ,
		-- R."Cost" as "PaidAmount",
	PT."PayTypeName",R."PaymentDetails",
			 PH."RequisitionNumber",
			 R."ReceiptId",RT."Name" as "AreaType",R."CreatedDate" "ReceiptDate",R."ReceiptTypeId",
			PA."FullName" as "PatientName",PA."Mobile" ,PA."UMRNo",
	R."CreatedBy",A."FullName" "ReceiptCreatedBy",AR."RoleName" 
	
		from "Receipt" R
		join "BookScanAppointment" PH on PH."BookScanAppointmentId"=R."RespectiveId" 
		join "Account" A on A."AccountId"=R."CreatedBy"
		join "Role" AR on AR."RoleId"=A."RoleId"
		 join "PayType" PT ON PT."PayTypeId" = R."PayTypeId"  
		join "ReceiptAreaType" RT on R."ReceiptAreaTypeId"=RT."ReceiptAreaTypeId"	
		left join "Patient" PA on PA."PatientId"=PH."PatientId"

	where  R."ReceiptAreaTypeId" in (10,11)
		--PH."LocationId"=2  and R."CreatedDate"::date='2023-04-14' 		
		and case when "accountid" is null then 1=1 else R."CreatedBy"="accountid" end and	
		case when "fromDate" is null then 1=1 else "fromDate"<= R."CreatedDate"::date end and
		case when "toDate" is null then 1=1 else R."CreatedDate"::date<=  "toDate" end and
		case when "locationid" is null then 1=1 else PH."LocationId" = "locationid" end
)
SELECT O."AccountId",O."ReceiptCreatedBy",O."RoleName",O."ReceiptDate",O."ReceiptId",O."ReceiptTypeId",
O."AreaType",O."RefId",
coalesce(O."PayTypeName"::character varying,'GRAND')"PayTypeName"
,O."PaymentDetails"--,coalesce(case when O."ReceiptTypeId"=2 then O."PaidAmount" end,0) as "RefundAmount" 
,sum(O."PaidAmount")-sum(O."RefundAmount") "PaidAmount",--O."RefundAmount",--O."BalanceAmount",sum(A."PaidAmount") "PaidAmount"
O."PatientName",O."UMRNo",O."Mobile"
from 
(
	Select  A."AccountId",AP."ReceiptCreatedBy",AP."RoleName",AP."ReceiptDate",AP."ReceiptId",AP."ReceiptTypeId",
AP."AreaType",AP."AppointmentNo" as "RefId",AP."PayTypeName",AP."PaymentDetails"
,AP."PaidAmount",AP."RefundAmount",--AP."BalanceAmount",
AP."PatientName",AP."UMRNo",AP."Mobile"
from accountdata A
join appointment AP on AP."CreatedBy"=A."AccountId"
UNION
	Select  A."AccountId",AP."ReceiptCreatedBy",AP."RoleName",AP."ReceiptDate",AP."ReceiptId",AP."ReceiptTypeId",
AP."AreaType",AP."AdmissionNo" as "RefId",AP."PayTypeName",AP."PaymentDetails"
,AP."PaidAmount",AP."RefundAmount",--AP."BalanceAmount",
AP."PatientName",AP."UMRNo",AP."Mobile"
from accountdata A
join admission AP on AP."CreatedBy"=A."AccountId"
UNION
Select  A."AccountId",AP."ReceiptCreatedBy",AP."RoleName",AP."ReceiptDate",AP."ReceiptId",AP."ReceiptTypeId",
AP."AreaType",AP."PatientId"::character varying as "RefId",AP."PayTypeName",AP."PaymentDetails"
,AP."PaidAmount",AP."RefundAmount",--AP."BalanceAmount",
AP."PatientName",AP."UMRNo",AP."Mobile"
from accountdata A
join patient AP on AP."CreatedBy"=A."AccountId"
UNION
Select  A."AccountId",AP."ReceiptCreatedBy",AP."RoleName",AP."ReceiptDate",AP."ReceiptId",AP."ReceiptTypeId",
AP."AreaType",AP."RequisitionNumber"::character varying as "RefId",AP."PayTypeName",AP."PaymentDetails"
,AP."PaidAmount",AP."RefundAmount",--AP."BalanceAmount",
AP."PatientName",AP."UMRNo",AP."Mobile"
from accountdata A
join lab AP on AP."CreatedBy"=A."AccountId"
UNION
Select  A."AccountId",AP."ReceiptCreatedBy",AP."RoleName",AP."ReceiptDate",AP."ReceiptId",AP."ReceiptTypeId",
AP."AreaType",AP."BillNumber"::character varying as "RefId",AP."PayTypeName",AP."PaymentDetails"
,AP."PaidAmount",AP."RefundAmount",--AP."BalanceAmount",
AP."PatientName",AP."UMRNo",AP."Mobile"
from accountdata A
join pharma AP on AP."CreatedBy"=A."AccountId"
	UNION
Select  A."AccountId",AP."ReceiptCreatedBy",AP."RoleName",AP."ReceiptDate",AP."ReceiptId",AP."ReceiptTypeId",
AP."AreaType",AP."RequisitionNumber"::character varying as "RefId",AP."PayTypeName",AP."PaymentDetails"
,AP."PaidAmount",AP."RefundAmount",--AP."BalanceAmount",
AP."PatientName",AP."UMRNo",AP."Mobile"
from accountdata A
join scan AP on AP."CreatedBy"=A."AccountId"	
	
)O

GROUP BY GROUPING SETS((O."AccountId",O."ReceiptCreatedBy",O."RoleName",O."ReceiptDate",
						O."ReceiptId",O."ReceiptTypeId",O."AreaType",O."RefId",O."PayTypeName",
						O."PaymentDetails",O."PatientName",O."UMRNo",O."Mobile"),(O."PayTypeName"), ())   

order by O."PayTypeName" asc, O."ReceiptDate" asc;

end
$BODY$;

ALTER FUNCTION public."collection_userLogin"(date, date, integer, integer)
    OWNER TO postgres;
---------------------------------------------------------------------------12June2023 Tej

DROP FUNCTION IF EXISTS public."udf_FetchPatients_For_AppointmentScheduleFollowUp"(character varying, character varying, character varying, character varying, integer);
-- FUNCTION: public.udf_FetchPatients_For_AppointmentScheduleFollowUp(character varying, character varying, character varying, character varying, integer)

-- DROP FUNCTION IF EXISTS public."udf_FetchPatients_For_AppointmentScheduleFollowUp"(character varying, character varying, character varying, character varying, integer);

CREATE OR REPLACE FUNCTION public."udf_FetchPatients_For_AppointmentScheduleFollowUp"(
	filter character varying DEFAULT NULL::text,
	"patientMobile" character varying DEFAULT NULL::text,
	"patientName" character varying DEFAULT NULL::text,
	"urlLink" character varying DEFAULT NULL::text,
	"appointmentId" integer DEFAULT NULL::integer)
    RETURNS TABLE("IdProofName" character varying, "RelativeName" character varying, "Relation" character varying, "EducationName" text, "HowDidYouKnow" text, "OccupationName" text, "PatientId" integer, "Salutation" character varying, "FirstName" text, "MiddleName" text, "LastName" text, "FullName" text, "DateOfBirth" date, "Age" smallint, "Gender" character, "MaritalStatus" character, "UMRNo" character varying, "Email" character varying, "Mobile" character varying, "StreetAddress" character varying, "Area" character varying, "City" character varying, "State" character varying, "Zipcode" character varying, "CountryId" integer, "ProfileImageUrl" text, "ThumbnailUrl" text, "Active" boolean, "CreatedBy" integer, "CreatedDate" timestamp without time zone, "ModifiedBy" integer, "ModifiedDate" timestamp without time zone, "Guid" uuid, "ReferralBy" integer, "ReferralCode" character varying, "AadharNo" character varying, "ReferredBy" character varying, "ReferredByName" character varying, "FatherOrHusband" text, "HWCPatientId" integer, "Education" character varying, "Occupation" character varying, "Religion" character varying, "Nationality" character varying, "PatientReferredById" integer, "IdProofValue" character varying, "IdProofId" integer, "BloodGroup" character varying, "Amount" numeric, "PaymentStatus" boolean, "TempPatient" boolean, "HowDidYouKnowId" integer, "EducationId" integer, "OccupationId" integer, "BirthMark1" text, "BirthMark2" text, "RelationType" text, "OccupationDetail" text, "IsNewPatient" boolean, "REGID" character varying, "REGNO" integer, "InsuranceCompanyId" integer, "ProviderId" integer, "AppointmentId" integer, "PatientType" character, "AppointmentNo" character varying, "AppointmentTime" time without time zone, "AppointmentEndTime" time without time zone, "AppointmentNotes" character varying, "CouponId" integer, "AppointmentAmount" numeric, "Discount" numeric, "Total" numeric, "Status" character, "PatientFamilyId" integer, "DepartmentId" integer, "PaymentType" character , "PaymentNumber" character varying, "AppointmentPaymentStatus" boolean, "VisitTypeId" integer, "ChargeTypesId" integer, "LocationId" integer, "AppointmentTypeId" integer, "PayTypeId" integer, "TokenNumber" integer, "SpecializationId" integer, "ProviderAvailabilityId" integer, "ConsultationTypeId" integer, "DoctorSpecializationChargeModuleDetailsId" integer, "OtherRemarks" character varying, "AuthorityMasterId" integer, "ReasonsId" integer, "Remarks" character varying, "ProviderName" character varying, "ModuleName" character varying, "AppointmentDate" timestamp without time zone, "isActiveAppointmentExists" boolean, "HWCName" character varying, "Description" text, "RowColor" text) 
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000

AS $BODY$
BEGIN

return query

with cts as (
select row_number() over(partition by a."PatientId" order by  a."AppointmentId" desc,
						 a."AppointmentDate" desc )"Max" ,a."PatientId",a."AppointmentId" 
	from "Appointment" a
join  "Patient" pat  on  a."PatientId"	=pat."PatientId"
	join "Provider" pr on a."ProviderId" = pr."ProviderId"
where a."Active"=true 	 
	--and	case when "filter" is null then 1=1 else (TRIM(UPPER(pat."FullName")) ILIKE '%' OR pat."UMRNo"  ilike'%'  OR pat."Mobile" ILIKE '%')|| "filter"||'%' end
	and case when "filter" is null then 1=1 else  TRIM(UPPER(pat."FullName")) ilike'%'|| "filter"||'%' OR  TRIM(UPPER(pat."UMRNo")) ilike'%'|| "filter"||'%' OR  TRIM(UPPER(pat."Mobile")) ilike'%'|| "filter"||'%'  end
	and	case when "patientMobile" is null then 1=1 else  pat."Mobile"  ilike'%'|| "patientMobile"||'%' end
	and	case when "patientName" is null then 1=1 else  pat."FullName"  ilike'%'|| "patientName"||'%' end
	and case when "appointmentId" is null then 1=1 else a."AppointmentId" = "appointmentId" end
)
, maxapt as (
select a.* from "Appointment" a
join cts on a."AppointmentId"=cts."AppointmentId"
where "Max"=1)

SELECT DISTINCT

id."IdProofName",pf."FullName" as "RelativeName",pf."Relation",
eid."Name" as "EducationName",hid."Name" as "HowDidYouKnow",oid."Name" as "OccupationName",

   pat."PatientId",pat. "Salutation",pat. "FirstName",pat. "MiddleName",pat. "LastName",pat. "FullName",pat. "DateOfBirth",pat. "Age",pat. "Gender",pat. "MaritalStatus",pat. "UMRNo",pat. "Email",pat. "Mobile",pat. "StreetAddress",pat. "AddressLine2" as "Area",pat. "City",pat. "State",pat. "Zipcode",pat. "CountryId"
,(CASE WHEN pat."ProfileImageUrl" IS NOT NULL THEN CONCAT("urlLink",'/', pat."Guid", '/', pat."ProfileImageUrl") ELSE '' END) AS "ProfileImageUrl"
,(CASE WHEN pat."ThumbnailUrl" IS NOT NULL THEN CONCAT("urlLink", '/', pat."Guid", '/', pat."ThumbnailUrl") ELSE '' END) AS "ThumbnailUrl"
,pat. "Active",pat. "CreatedBy",pat. "CreatedDate",pat. "ModifiedBy",pat. "ModifiedDate",pat. "Guid",pat. "ReferralBy",pat. "ReferralCode",pat. "AadharNo",referred."Name" as "ReferredBy",pat. "ReferredByName",pat. "FatherOrHusband",pat. "HWCPatientId",pat. "Education",pat. "Occupation",pat. "Religion",pat. "Nationality",pat. "PatientReferredById",pat. "IdProofValue",pat. "IdProofId",pat. "BloodGroup",pat. "Amount",pat. "PaymentStatus",pat. "TempPatient",pat. "HowDidYouKnowId",pat. "EducationId",pat. "OccupationId",pat. "BirthMark1",pat. "BirthMark2",pat. "RelationType",pat. "OccupationDetail",pat. "IsNewPatient",pat. "REGID",pat. "REGNO",pat. "InsuranceCompanyId",
	
	
	apt."ProviderId",	
	 apt."AppointmentId", 
	 apt."PatientType", 
	 apt."AppointmentNo"
	 ,apt."AppointmentTime"
	 ,apt. "AppointmentEndTime"
	 ,apt. "AppointmentNotes",
	 apt."CouponId",
	 apt. "Amount" as "AppointmentAmount",
	 apt."Discount"
	 ,apt. "Total"
	 ,apt. "Status"
	 ,apt. "PatientFamilyId"
	 ,apt. "DepartmentId"
	 ,apt. "PaymentType"
	 ,apt. "PaymentNumber"
	 ,apt. "PaymentStatus"
	 , apt."VisitTypeId"
	 , apt."ChargeTypesId"
	 , apt."LocationId"
	 , apt."AppointmentTypeId"
	 , apt."PayTypeId"
	 , apt."TokenNumber"
	 , apt."SpecializationId"
	 , apt."ProviderAvailabilityId"
	 , apt."ConsultationTypeId"
	 , apt."DoctorSpecializationChargeModuleDetailsId"
	 , apt."OtherRemarks"
	 , apt."AuthorityMasterId"
	 , apt."ReasonsId"
	 , apt."Remarks"	 
	 
	,pr."FullName" as "ProviderName",MM."ModuleName"
,(max(apt."AppointmentDate")over(partition by apt."PatientId")::text ||' ' || max(apt."AppointmentTime")over(partition by apt."PatientId",apt."AppointmentDate")::text)::timestamp as "AppointmentDate",
(case when (max(apt."AppointmentDate")over(partition by apt."PatientId")::text ||' ' || max(apt."AppointmentTime")over(partition by apt."PatientId")::text)::timestamp > now() at time zone 'UTC-5:30' then true else false end)"isActiveAppointmentExists"
, HWC."HWCName", HWC."Description", HWC."RowColor"
FROM "Patient" pat  
left join maxapt apt on apt."PatientId" = pat."PatientId" and apt."Status" <> 'C' and apt."Active"=true
left join "Provider" pr on pr."ProviderId" = apt."ProviderId"
left join "HWCPatient"  HWC on HWC."HWCPatientId" = pat."HWCPatientId"
LEFT JOIN "PatientReferredBy" referred ON referred."PatientReferredById" = pat."PatientReferredById"
left join "IdProof" id on id."IdProofId" = pat."IdProofId"
left join "HowDidYouKnow" hid on hid."HowDidYouKnowId" = pat."HowDidYouKnowId"
left join "Education" eid on eid."EducationId" = pat."EducationId"
left join "Occupation" oid on oid."OccupationId" = pat."OccupationId"
left join "PatientFamily" pf on pf."PatientId" = pat."PatientId"
left join "WebNotification" wn on wn."PatientId" = pat."PatientId"
left join "ModulesMaster" MM on MM."ModulesMasterId" = wn."ModulesMasterId"
 WHERE  pat."Active" IS TRUE 
--and	case when "filter" is null then 1=1 else (TRIM(UPPER(pat."FullName")) ILIKE '%' OR pat."UMRNo"  ilike'%'  OR pat."Mobile" ILIKE '%')|| "filter"||'%' end
and case when "filter" is null then 1=1 else  TRIM(UPPER(pat."FullName")) ilike'%'|| "filter"||'%' OR  TRIM(UPPER(pat."UMRNo")) ilike'%'|| "filter"||'%' OR  TRIM(UPPER(pat."Mobile")) ilike'%'|| "filter"||'%'  end
and	case when "patientMobile" is null then 1=1 else  pat."Mobile"  ilike'%'|| "patientMobile"||'%' end
and	case when "patientName" is null then 1=1 else  pat."FullName"  ilike'%'|| "patientName"||'%' end
and case when "appointmentId" is null then 1=1 else apt."AppointmentId" = "appointmentId" end
;

END
$BODY$;

ALTER FUNCTION public."udf_FetchPatients_For_AppointmentScheduleFollowUp"(character varying, character varying, character varying, character varying, integer)
    OWNER TO postgres;

-------------------------------------------------------------------------13JuneSrilekha
-- FUNCTION: public.udf_uiReport_fetch_Appointments_Location(integer, text, integer[], integer[], integer[], text, integer[], text, text, integer, date, date, integer[], boolean, text[], integer, integer)

-- DROP FUNCTION public."udf_uiReport_fetch_Appointments_Location"(integer, text, integer[], integer[], integer[], text, integer[], text, text, integer, date, date, integer[], boolean, text[], integer, integer);
DROP FUNCTION IF EXISTS public."udf_uiReport_fetch_Appointments_Location"(integer, text, integer[], integer[], integer[], text, integer[], text, text, integer, date, date, integer[], boolean, text[], integer, integer);
CREATE OR REPLACE FUNCTION public."udf_uiReport_fetch_Appointments_Location"(
	locationid integer DEFAULT NULL::integer,
	"appointmentNo" text DEFAULT NULL::text,
	"departmentId" integer[] DEFAULT NULL::integer[],
	"providerId" integer[] DEFAULT NULL::integer[],
	"patientId" integer[] DEFAULT NULL::integer[],
	"uMRNo" text DEFAULT NULL::text,
	"patientReferredById" integer[] DEFAULT NULL::integer[],
	"referredByName" text DEFAULT NULL::text,
	mobile text DEFAULT NULL::text,
	"payTypeId" integer DEFAULT NULL::integer,
	"fromDate" date DEFAULT NULL::date,
	"toDate" date DEFAULT NULL::date,
	"appointmentTypeId" integer[] DEFAULT NULL::integer[],
	"paymentStatus" boolean DEFAULT NULL::boolean,
	status text[] DEFAULT NULL::text[],
	"pageIndex" integer DEFAULT 0,
	"pageSize" integer DEFAULT 10)
    RETURNS TABLE("DepartmentId" text, "DepartmentName" character varying, "ProviderId" text, "ProviderName" character varying, "AppointmentTypeName" character varying, "AppointmentDate" date, "AppointmentNo" character varying, "PatientId" integer, "Name" character varying, "ReferredByName" character varying, "PatientName" character varying, "PatientAge" smallint, "UMRNo" character varying, "Mobile" character varying, "PatientGender" character, "AppointmentTime" time without time zone, "VisitType" character, "PaymentType" character varying, "PaymentNumber" character varying, "TotalAppointments" bigint, "TotalAmount" bigint, "TotalAmountStr" text, "ReceiptCreatedByName" text, "ReceiptDate" timestamp without time zone, "ReceiptId" integer, "StreetAdress" character varying, "City" character varying, "State" character varying, "FatherOrHusband" text, "PaymentStatus" boolean, "EncounterType" encountertype_elements, "Status" text, "TypeOfPayment" character) 
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000

AS $BODY$
BEGIN

return query 

with cts as (select coalesce(A."DepartmentId"::text,'GrandTotal') "DepartmentId",
			 A."ProviderId"::text as "ProviderId", 
			 A."AppointmentDate",A."AppointmentTypeId",
			ATN."Name" "AppointmentTypeName",
			 A."AppointmentNo",A."PatientId" "PatientId",PRB."Name",Pa."ReferredByName",
			 Pa."FullName",Pa."UMRNo",Pa."Mobile",A."AppointmentTime",A."VisitType",
			 case when ATN."Name"='Follow Up' and sum(A."Total")=0 then 'Free Follow Up'
			 else PT."PayTypeName" end as "PaymentType" ,A."PaymentNumber",
			 A."AppointmentId",
			 case when A."Status"='B' then 'Booked' when A."Status"='R' then 'Rescheduled' when A."Status"='C' then 'Cancel' end::text as "Status",
			 COUNT(A."AppointmentNo") as "TotalAppointments" ,sum(R."Cost")::text as "TotalAmountStr" ,
			 sum(R."Cost")::bigint as "TotalAmount" ,
			 Pa."FatherOrHusband",
			 A."PaymentStatus",
			 A."EncounterType",
			 A."PaymentType" as "TypeOfPayment"
			 from "Appointment" A
 			left join "Patient" Pa on Pa."PatientId"::text=A."PatientId"::text
			 left join "PayType" PT on PT."PayTypeId"=A."PayTypeId"
			 left join "PatientReferredBy" PRB on PRB."PatientReferredById"::text=Pa."PatientReferredById"::text			
		left join "AppointmentType" ATN on A."AppointmentTypeId"=ATN."AppointmentTypeId"
			 left Join "Receipt" R on R."RespectiveId"=A."AppointmentId"  and R."ReceiptAreaTypeId"=4
where 
			 --A."Status"<>'C' and 
case when "departmentId" is null then 1=1 else  A."DepartmentId"  = any("departmentId") end and 
CASE WHEN (locationId IS NULL OR locationId=0) THEN 1=1 ELSE A."LocationId"=locationId END and
case when "patientId" is null then 1=1 else  Pa."PatientId"  = any("patientId") end and 
case when "appointmentNo" is null then 1=1 when "appointmentNo" ='' then 1=1 else A."AppointmentNo" ilike'%'||"appointmentNo" ||'%' end  and
case when "providerId" is null then 1=1 else  A."ProviderId"  = any("providerId") end and 
case when "uMRNo" is null then 1=1 when "uMRNo" ='' then 1=1 else Pa."UMRNo" ilike'%'||"uMRNo" ||'%' end  and
case when "patientReferredById" is null then 1=1 else  Pa."PatientReferredById"  = any("patientReferredById") end and 
case when "appointmentTypeId" is null then 1=1 else  ATN."AppointmentTypeId"  = any("appointmentTypeId") end and 
case when "referredByName" is null then 1=1 when "referredByName" ='' then 1=1 else Pa."ReferredByName" ilike'%'||"referredByName" ||'%' end and 
case when "mobile" is null then 1=1 when "mobile" ='' then 1=1 else Pa."Mobile" ilike'%'||"mobile" ||'%' end  and
case when "payTypeId" is null then 1=1  else A."PayTypeId" ="payTypeId" end  and
case when "fromDate" is null then 1=1 else "fromDate" <=A."AppointmentDate" and A."AppointmentDate" <="toDate" end and
case when "paymentStatus" is null then 1=1  else A."PaymentStatus" ="paymentStatus" end			 
and case when "status" is null then 1=1 else  A."Status"  =any("status") end	
			 
GROUP BY GROUPING SETS((A."DepartmentId",A."ProviderId",A."PatientId",PRB."Name",
						Pa."ReferredByName",Pa."FullName",Pa."UMRNo",Pa."Mobile",A."AppointmentDate",A."AppointmentTime",
						A."AppointmentNo",A."AppointmentTypeId",
						ATN."Name" ,
						A."VisitType",
						PT."PayTypeName",A."PaymentNumber",
						A."AppointmentId",
						A."Status",Pa."FatherOrHusband",A."PaymentStatus",A."EncounterType",A."PaymentType"), (A."DepartmentId",A."ProviderId"), ())     
order by A."AppointmentId")

select A."DepartmentId",coalesce(D."DepartmentName",'GrandTotal') "DepartmentName",
case when A."AppointmentNo" is null then 'Total'  else A."ProviderId" end "ProviderId",
case when A."AppointmentNo" is null  then 'Total'  else  Pr."FullName"  end  as "ProviderName",
 ATN."Name" "AppointmentTypeName",
A."AppointmentDate",
A."AppointmentNo",A."PatientId",
case when A."AppointmentNo" is null  then null else PRB."Name"::varchar end as "Name",
case when A."AppointmentNo" is null  then null else Pa."ReferredByName"::varchar end as "ReferredByName",
case when A."AppointmentNo" is null  then null else Pa."FullName"::varchar end as "PatientName",
case when A."AppointmentNo" is null  then null else Pa."Age" end  "PatientAge",
case when A."AppointmentNo" is null  then null else Pa."UMRNo" end  "UMRNo",
case when A."AppointmentNo" is null  then null else Pa."Mobile" end  "Mobile",
case when A."AppointmentNo" is null  then null else Pa."Gender" end "PatientGender",
A."AppointmentTime",
A."VisitType",A."PaymentType",A."PaymentNumber",A."TotalAppointments",A."TotalAmount",A."TotalAmountStr",
 CA."FullName"  "ReceiptCreatedByName", R."CreatedDate" "ReceiptDate",R."ReceiptId",
 case when A."AppointmentNo" is null  then null else Pa."StreetAddress" end "StreetAddress",
case when A."AppointmentNo" is null  then null else Pa."City" end "City",
case when A."AppointmentNo" is null  then null else Pa."State" end "State",
A."FatherOrHusband",
A."PaymentStatus",A."EncounterType",A."Status",A."TypeOfPayment"
from cts A
left join "Department" D on A."DepartmentId"=D."DepartmentId"::text
left join "Provider" Pr on Pr."ProviderId"::text=A."ProviderId"
left join "Patient" Pa on Pa."PatientId"::text=A."PatientId"::text
left Join "Receipt" R on R."RespectiveId"=A."AppointmentId"  and R."ReceiptAreaTypeId"=4
Left Join "Account" CA on CA."AccountId"=R."CreatedBy"
left join "PatientReferredBy" PRB on PRB."PatientReferredById"::text=Pa."PatientReferredById"::text
 left join  "AppointmentType" ATN on ATN."AppointmentTypeId"=A."AppointmentTypeId"
order by A."AppointmentId"
 ;

END

$BODY$;

ALTER FUNCTION public."udf_uiReport_fetch_Appointments_Location"(integer, text, integer[], integer[], integer[], text, integer[], text, text, integer, date, date, integer[], boolean, text[], integer, integer)
    OWNER TO postgres;
-------------------------------------------14June2023 Srilekha
alter table if exists "MasterBill"
add column  if not exists "LocationId" integer,
add column if not exists "ReceiptAreaTypeId" integer;



alter table if exists "BookScanAppointment"
add column if not exists "PaymentType" character(1);

DO $$                  
    BEGIN 
        IF EXISTS
            ( SELECT 1
              FROM   information_schema.tables 
              WHERE  table_schema = 'public'
              AND    table_name = 'BookScanAppointment'
            )
        THEN
            UPDATE "BookScanAppointment"
            SET "PaymentType" = 'F'
            where "PaymentStatus" = true;
        END IF ;
    END
   $$ ;

-------------------------------------------------------13June2023 Sravani
CREATE SEQUENCE IF NOT EXISTS "ScanAppointmentNotice_ScanAppointmentNoticeId_seq"
    INCREMENT 1
    START 1
    MINVALUE 1
    MAXVALUE 9223372036854775807
    CACHE 1;

CREATE TABLE IF NOT EXISTS "ScanAppointmentNotice"
(
    "ScanAppointmentNoticeId" integer NOT NULL DEFAULT nextval('"ScanAppointmentNotice_ScanAppointmentNoticeId_seq"'::regclass),
    "LocationId" integer,
    "MachineId" integer,
    "FromDate" timestamp(6) without time zone,
    "ToDate" timestamp(6) without time zone,
    "Description" character varying(500) COLLATE pg_catalog."default",
    "Active" boolean NOT NULL,
    "CreatedBy" integer NOT NULL,
    "CreatedDate" timestamp(6) without time zone,
    "ModifiedBy" integer,
    "ModifiedDate" timestamp(6) without time zone,
    CONSTRAINT "ScanAppointmentNoticeId_pkey" PRIMARY KEY ("ScanAppointmentNoticeId"),
    CONSTRAINT "FK_ScanAppointmentNotice_CreatedBy" FOREIGN KEY ("CreatedBy")
        REFERENCES "Account" ("AccountId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE CASCADE,
    CONSTRAINT "FK_ScanAppointmentNotice_LocationId" FOREIGN KEY ("LocationId")
        REFERENCES "Location" ("LocationId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE CASCADE,
    CONSTRAINT "FK_ScanAppointmentNotice_ModifiedBy" FOREIGN KEY ("ModifiedBy")
        REFERENCES "Account" ("AccountId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE CASCADE,
    CONSTRAINT "FK_ScanAppointmentNotice_MachineId" FOREIGN KEY ("MachineId")
        REFERENCES "ScanMachineMaster" ("ScanMachineMasterId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE CASCADE
);

INSERT INTO public."ScanLogType"("LogTypeName","Active")
SELECT 'ScanAppointmentNotice', true
WHERE
NOT EXISTS (
SELECT "LogTypeName" FROM public."ScanLogType" WHERE "LogTypeName" = 'ScanAppointmentNotice'
);
-------------------------------------------------------15June Sai Pavan
INSERT INTO public."Settings"("Name","Type","Active","Description")
SELECT 'WhatsAppMsgService','Message',true,'Choose to Enable/Disable the button for whatsapp message service'
WHERE
NOT EXISTS (
SELECT "Name" FROM public."Settings" WHERE "Name" = 'LabBillingEmergency'
);


INSERT INTO public."Settings"("Name","Type","Active","Description")
SELECT 'LabBillingEmergency','Column',true,'Choose to Enable/Disable the column and button for LabBillingEmergency'
WHERE
NOT EXISTS (
SELECT "Name" FROM public."Settings" WHERE "Name" = 'LabBillingEmergency'
);

-----------------------------------------------------15June2023 tej
alter table if exists "ScanAppointmentNotice" 
add column if not exists "Availability" text;
				
alter table if exists "ScanAppointmentNotice" 
add column if not exists "AvailableDays" text;
-----------------------------------------------------15June2023 Srilekha
alter table if exists "PharmacySaleHeader"
add column if not exists "PaymentType" character(1);

DO $$                  
    BEGIN 
        IF EXISTS
            ( SELECT 1
              FROM   information_schema.tables 
              WHERE  table_schema = 'public'
              AND    table_name = 'PharmacySaleHeader'
            )
        THEN
            UPDATE "PharmacySaleHeader"
            SET "PaymentType" = 'F'
            where "PaymentStatus" = true;
        END IF ;
    END
   $$ ;


------------------------------------------------15June Kalyan
alter table IF EXISTS "LabSampleCollection" 
add column If not exists "LocationId" integer,
DROP CONSTRAINT IF EXISTS "LabSampleCollection_LocationId_fkey",
ADD CONSTRAINT "LabSampleCollection_LocationId_fkey" FOREIGN KEY ("LocationId")
        REFERENCES "Location" ("LocationId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION;
--------------------------------------------------------------15 June Srilekha
-- FUNCTION: public.udf_PharmacyBills_Report(text, integer, character varying, character varying, integer, integer, integer, timestamp without time zone, timestamp without time zone, text, integer, text);
-- DROP FUNCTION public."udf_PharmacyBills_Report"(text, integer, character varying, character varying, integer, integer, integer, timestamp without time zone, timestamp without time zone, text, integer, text);
DROP FUNCTION public."udf_PharmacyBills_Report"(text, integer, character varying, character varying, integer, integer, integer, timestamp without time zone, timestamp without time zone, text, integer, text);
CREATE OR REPLACE FUNCTION public."udf_PharmacyBills_Report"(
	"billNumber" text DEFAULT NULL::text,
	"patientId" integer DEFAULT NULL::integer,
	"patientMobile" character varying DEFAULT NULL::text,
	"uMRNo" character varying DEFAULT NULL::text,
	"payTypeId" integer DEFAULT NULL::integer,
	"providerId" integer DEFAULT NULL::integer,
	"createdBy" integer DEFAULT NULL::integer,
	"fromDate" timestamp without time zone DEFAULT (now())::timestamp without time zone,
	"toDate" timestamp without time zone DEFAULT (now())::timestamp without time zone,
	"retailName" text DEFAULT NULL::text,
	"retailPharmacyId" integer DEFAULT NULL::integer,
	"locationId" text DEFAULT NULL::text)
    RETURNS TABLE("PharmacySaleHeaderId" integer, "BillNumber" character varying, "SaleDate" timestamp without time zone, "PatientName" character varying, "PatientMobile" character varying, "UMRNo" character varying, "PaidVia" character varying, "PaymentNumber" character varying, "CreatedByName" text, "RoleName" character varying, "ProviderName" character varying, "TotalAmount" numeric, "RetailName" text, "OverallTaxes" numeric, "LocationName" character varying, "TypeOfPayment" character) 
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000

AS $BODY$
BEGIN

return query

select A."PharmacySaleHeaderId" ,A."BillNumber",A."SaleDate",A."PatientName",A."Mobile" 
,A."UMRNo",A."PaidVia",A."PaymentNumber",A."CreatedByName",A."Role" ,
A."ProviderName", sum(A."Cost") as "TotalAmount"  ,A."RetailName",A."OverallTaxes",A."LocationName",
A."TypeOfPayment" from (
select PH."PharmacySaleHeaderId" ,PH."BillNumber",PH."CreatedDate" "SaleDate",PH."PatientName",PH."Mobile" 
,Pa."UMRNo",PT."PayTypeName" as "PaidVia",PH."PaymentNumber",A."FullName" 
"CreatedByName",R."RoleName" "Role" ,
PH."ProviderName", RC."Cost"  ,RP."RetailName",PH."OverallTaxes",L."Name" as "LocationName",
PH."PaymentType" as "TypeOfPayment",RC."ReceiptId"
from  "PharmacySaleHeader" PH
 join "Patient" Pa on Pa."PatientId"::text=PH."PatientId"::text
join "Account" A on A."AccountId"=PH."CreatedBy"
join "Role" R on R."RoleId"=A."RoleId"
join "PharmacySaleDetail" PSD on PSD."PharmacySaleHeaderId"=PH."PharmacySaleHeaderId"
join "PharmacyRetailStock" PRS on PRS."PharmacyRetailStockId"=PSD."PharmacyRetailStockId"
join "RetailWareHouseLink" RWL on RWL."RetailWareHouseLinkId" = PRS."RetailWareHouseLinkId"
join "RetailPharmacy" RP on RP."RetailPharmacyId"=RWL."RetailPharmacyId"
join "Location" L on L."LocationId" = PH."LocationId"
join "PayType" PT on PT."PayTypeId"=PH."PayTypeId"
	 
left Join "Receipt" RC on RC."RespectiveId"=PH."PharmacySaleHeaderId"  and RC."ReceiptAreaTypeId"=1
where	case when "billNumber" is null then 1=1 else  PH."BillNumber" ilike '%' || "billNumber" ||'%' end and 
case when "patientId" is null then 1=1 else PH."PatientId"="patientId" end and
	
	case when "patientMobile" is null then 1=1 else  PH."Mobile" ilike '%' || "patientMobile" ||'%' end  and
	case when "uMRNo" is null then 1=1 else  Pa."UMRNo" ilike '%' || "uMRNo" ||'%' end  and
				case when "payTypeId" is null then 1=1 else  PT."PayTypeId" = "payTypeId" end  and
	case when "providerId" is null then 1=1 else  PH."ProviderId" ="providerId"  end  and
		case when "createdBy" is null then 1=1 else  A."AccountId"="createdBy" end and
 case when "fromDate" is null then 1=1 else PH."SaleDate" >= "fromDate" end and 
 case when "toDate" is null then 1=1 else PH."SaleDate" <= "toDate" end  and
 case when "retailName" is null then 1=1 else  RP."RetailName" ilike '%' || "retailName" ||'%' end and 
 	case when "retailPharmacyId" is null then 1=1 else  RP."RetailPharmacyId" = "retailPharmacyId" end and 
case when "locationId" is null then 1=1 else PH."LocationId" = "locationId"::int end
group by PH."PharmacySaleHeaderId" ,PH."BillNumber",PH."SaleDate", PH."OverallNetAmount",PH."PatientName",PH."Mobile",Pa."UMRNo",PT."PayTypeName"
, PH."PaymentNumber", A."FullName" 
,R."RoleName" ,PH."ProviderName",RP."RetailName",PH."OverallTaxes",L."Name",RC."ReceiptId" ) A
group by A."PharmacySaleHeaderId" ,A."BillNumber",A."SaleDate",A."PatientName",A."Mobile" 
,A."UMRNo",A."PaidVia",A."PaymentNumber",A."CreatedByName",A."Role" ,
A."ProviderName"  ,A."RetailName",A."OverallTaxes",A."LocationName",
A."TypeOfPayment",A."ReceiptId"
order by A."SaleDate" desc;
END
$BODY$;

ALTER FUNCTION public."udf_PharmacyBills_Report"(text, integer, character varying, character varying, integer, integer, integer, timestamp without time zone, timestamp without time zone, text, integer, text)
    OWNER TO postgres;
---------------------------------------------------------------------------------------------------15 June Srilekha
-- FUNCTION: public.udf_uiReport_fetch_Appointments_Location(integer, text, integer[], integer[], integer[], text, integer[], text, text, integer, date, date, integer[], boolean, text[], integer, integer)

-- DROP FUNCTION public."udf_uiReport_fetch_Appointments_Location"(integer, text, integer[], integer[], integer[], text, integer[], text, text, integer, date, date, integer[], boolean, text[], integer, integer);

CREATE OR REPLACE FUNCTION public."udf_uiReport_fetch_Appointments_Location"(
	locationid integer DEFAULT NULL::integer,
	"appointmentNo" text DEFAULT NULL::text,
	"departmentId" integer[] DEFAULT NULL::integer[],
	"providerId" integer[] DEFAULT NULL::integer[],
	"patientId" integer[] DEFAULT NULL::integer[],
	"uMRNo" text DEFAULT NULL::text,
	"patientReferredById" integer[] DEFAULT NULL::integer[],
	"referredByName" text DEFAULT NULL::text,
	mobile text DEFAULT NULL::text,
	"payTypeId" integer DEFAULT NULL::integer,
	"fromDate" date DEFAULT NULL::date,
	"toDate" date DEFAULT NULL::date,
	"appointmentTypeId" integer[] DEFAULT NULL::integer[],
	"paymentStatus" boolean DEFAULT NULL::boolean,
	status text[] DEFAULT NULL::text[],
	"pageIndex" integer DEFAULT 0,
	"pageSize" integer DEFAULT 10)
    RETURNS TABLE("DepartmentId" text, "DepartmentName" character varying, "ProviderId" text, "ProviderName" character varying, "AppointmentTypeName" character varying, "AppointmentDate" date, "AppointmentNo" character varying, "PatientId" integer, "Name" character varying, "ReferredByName" character varying, "PatientName" character varying, "PatientAge" smallint, "UMRNo" character varying, "Mobile" character varying, "PatientGender" character, "AppointmentTime" time without time zone, "VisitType" character, "PaymentType" character varying, "PaymentNumber" character varying, "TotalAppointments" bigint, "TotalAmount" bigint, "TotalAmountStr" text, "ReceiptCreatedByName" text, "ReceiptDate" timestamp without time zone, "ReceiptId" integer, "StreetAdress" character varying, "City" character varying, "State" character varying, "FatherOrHusband" text, "PaymentStatus" boolean, "EncounterType" encountertype_elements, "Status" text, "TypeOfPayment" character) 
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000

AS $BODY$
BEGIN

return query 

with cts as (select coalesce(A."DepartmentId"::text,'GrandTotal') "DepartmentId",
			 A."ProviderId"::text as "ProviderId", 
			 A."AppointmentDate",A."AppointmentTypeId",
			ATN."Name" "AppointmentTypeName",
			 A."AppointmentNo",A."PatientId" "PatientId",PRB."Name",Pa."ReferredByName",
			 Pa."FullName",Pa."UMRNo",Pa."Mobile",A."AppointmentTime",A."VisitType",
			 case when ATN."Name"='Follow Up' and sum(A."Total")=0 then 'Free Follow Up'
			 else PT."PayTypeName" end as "PaymentType" ,A."PaymentNumber",
			 A."AppointmentId",
			 case when A."Status"='B' then 'Booked' when A."Status"='R' then 'Rescheduled' when A."Status"='C' then 'Cancel' end::text as "Status",
			 COUNT(A."AppointmentNo") as "TotalAppointments" ,sum(R."Cost")::text as "TotalAmountStr" ,
			 sum(R."Cost")::bigint as "TotalAmount" ,
			 Pa."FatherOrHusband",
			 A."PaymentStatus",
			 A."EncounterType",
			 A."PaymentType" as "TypeOfPayment",R."ReceiptId"
			 from "Appointment" A
 			left join "Patient" Pa on Pa."PatientId"::text=A."PatientId"::text
			 
			 left join "PatientReferredBy" PRB on PRB."PatientReferredById"::text=Pa."PatientReferredById"::text			
		left join "AppointmentType" ATN on A."AppointmentTypeId"=ATN."AppointmentTypeId"
			 left Join "Receipt" R on R."RespectiveId"=A."AppointmentId"  and R."ReceiptAreaTypeId"=4
			  left join "PayType" PT on PT."PayTypeId"=R."PayTypeId"
where 
			 --A."Status"<>'C' and 
case when "departmentId" is null then 1=1 else  A."DepartmentId"  = any("departmentId") end and 
CASE WHEN (locationId IS NULL OR locationId=0) THEN 1=1 ELSE A."LocationId"=locationId END and
case when "patientId" is null then 1=1 else  Pa."PatientId"  = any("patientId") end and 
case when "appointmentNo" is null then 1=1 when "appointmentNo" ='' then 1=1 else A."AppointmentNo" ilike'%'||"appointmentNo" ||'%' end  and
case when "providerId" is null then 1=1 else  A."ProviderId"  = any("providerId") end and 
case when "uMRNo" is null then 1=1 when "uMRNo" ='' then 1=1 else Pa."UMRNo" ilike'%'||"uMRNo" ||'%' end  and
case when "patientReferredById" is null then 1=1 else  Pa."PatientReferredById"  = any("patientReferredById") end and 
case when "appointmentTypeId" is null then 1=1 else  ATN."AppointmentTypeId"  = any("appointmentTypeId") end and 
case when "referredByName" is null then 1=1 when "referredByName" ='' then 1=1 else Pa."ReferredByName" ilike'%'||"referredByName" ||'%' end and 
case when "mobile" is null then 1=1 when "mobile" ='' then 1=1 else Pa."Mobile" ilike'%'||"mobile" ||'%' end  and
case when "payTypeId" is null then 1=1  else A."PayTypeId" ="payTypeId" end  and
case when "fromDate" is null then 1=1 else "fromDate" <=A."AppointmentDate" and A."AppointmentDate" <="toDate" end and
case when "paymentStatus" is null then 1=1  else A."PaymentStatus" ="paymentStatus" end			 
and case when "status" is null then 1=1 else  A."Status"  =any("status") end	
			 
GROUP BY GROUPING SETS((A."DepartmentId",A."ProviderId",A."PatientId",PRB."Name",
						Pa."ReferredByName",Pa."FullName",Pa."UMRNo",Pa."Mobile",A."AppointmentDate",A."AppointmentTime",
						A."AppointmentNo",A."AppointmentTypeId",
						ATN."Name" ,
						A."VisitType",
						PT."PayTypeName",A."PaymentNumber",
						A."AppointmentId",R."ReceiptId",
						A."Status",Pa."FatherOrHusband",A."PaymentStatus",A."EncounterType",A."PaymentType"), (A."DepartmentId",A."ProviderId"), ())     
order by A."AppointmentId")

select A."DepartmentId",coalesce(D."DepartmentName",'GrandTotal') "DepartmentName",
case when A."AppointmentNo" is null then 'Total'  else A."ProviderId" end "ProviderId",
case when A."AppointmentNo" is null  then 'Total'  else  Pr."FullName"  end  as "ProviderName",
 ATN."Name" "AppointmentTypeName",
A."AppointmentDate",
A."AppointmentNo",A."PatientId",
case when A."AppointmentNo" is null  then null else PRB."Name"::varchar end as "Name",
case when A."AppointmentNo" is null  then null else Pa."ReferredByName"::varchar end as "ReferredByName",
case when A."AppointmentNo" is null  then null else Pa."FullName"::varchar end as "PatientName",
case when A."AppointmentNo" is null  then null else Pa."Age" end  "PatientAge",
case when A."AppointmentNo" is null  then null else Pa."UMRNo" end  "UMRNo",
case when A."AppointmentNo" is null  then null else Pa."Mobile" end  "Mobile",
case when A."AppointmentNo" is null  then null else Pa."Gender" end "PatientGender",
A."AppointmentTime",
A."VisitType",A."PaymentType",A."PaymentNumber",A."TotalAppointments",A."TotalAmount",A."TotalAmountStr",
 CA."FullName"  "ReceiptCreatedByName", R."CreatedDate" "ReceiptDate",R."ReceiptId",
 case when A."AppointmentNo" is null  then null else Pa."StreetAddress" end "StreetAddress",
case when A."AppointmentNo" is null  then null else Pa."City" end "City",
case when A."AppointmentNo" is null  then null else Pa."State" end "State",
A."FatherOrHusband",
A."PaymentStatus",A."EncounterType",A."Status",A."TypeOfPayment"
from cts A
left join "Department" D on A."DepartmentId"=D."DepartmentId"::text
left join "Provider" Pr on Pr."ProviderId"::text=A."ProviderId"
left join "Patient" Pa on Pa."PatientId"::text=A."PatientId"::text
left Join "Receipt" R on R."RespectiveId"=A."AppointmentId"  and R."ReceiptAreaTypeId"=4 and R."ReceiptId"=A."ReceiptId"
Left Join "Account" CA on CA."AccountId"=R."CreatedBy"
left join "PatientReferredBy" PRB on PRB."PatientReferredById"::text=Pa."PatientReferredById"::text
 left join  "AppointmentType" ATN on ATN."AppointmentTypeId"=A."AppointmentTypeId"
order by A."AppointmentId"
 ;

END

$BODY$;

ALTER FUNCTION public."udf_uiReport_fetch_Appointments_Location"(integer, text, integer[], integer[], integer[], text, integer[], text, text, integer, date, date, integer[], boolean, text[], integer, integer)
    OWNER TO postgres;


----------------------------------------------15June 2023 Kalyan

alter table IF EXISTS "LabMainDetail" 
add column If not exists "LabVacutainerId" integer,
DROP CONSTRAINT IF EXISTS "LabMainDetail_LabVacutainerId_fkey",
ADD CONSTRAINT "LabMainDetail_LabVacutainerId_fkey" FOREIGN KEY ("LabVacutainerId")
        REFERENCES "LabVacutainer" ("LabVacutainerId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION;

----------------------------------------Android Pavan

create sequence IF NOT EXISTS "LabVacutainer_LabVacutainerId_seq";
CREATE TABLE IF NOT EXISTS public."LabVacutainer"
(
    "LabVacutainerId" integer NOT NULL DEFAULT nextval('"LabVacutainer_LabVacutainerId_seq"'::regclass),
    "LabVacutainerName" character varying(255) COLLATE pg_catalog."default" NOT NULL,
    "Active" boolean NOT NULL DEFAULT true,
    "CreatedBy" integer NOT NULL,
    "CreatedDate" timestamp(6) without time zone NOT NULL,
    "ModifiedBy" integer,
    "ModifiedDate" timestamp(6) without time zone,
    CONSTRAINT "LabVacutainer_pkey" PRIMARY KEY ("LabVacutainerId"),
    CONSTRAINT "FK_LabVacutainer_CreatedBy" FOREIGN KEY ("CreatedBy")
        REFERENCES public."Account" ("AccountId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE CASCADE,
    CONSTRAINT "FK_LabVacutainer_ModifiedBy" FOREIGN KEY ("ModifiedBy")
        REFERENCES public."Account" ("AccountId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE CASCADE
);

---------------------------------------Kalyan 20June2023
alter table IF EXISTS "LabMainDetail" 
add column If not exists "NoOfSamplesCollect" integer,
add column If not exists "NoOfSamplesCollectText" character varying COLLATE pg_catalog."default";

--------------------------------------Manish 17June2023
alter table IF EXISTS "NewLabBookingDetail" 
		add column if not exists "TechnicianId" int references "Account"("AccountId"),
		add column if not exists "TechnicianComment" text,
		add column if not exists "TechnicianVerificationDate" timestamp without time zone;
--------------------
INSERT INTO public."LabBookingStatus"("Status","Active")
SELECT 'TechnicianVerified', true
WHERE
NOT EXISTS (
SELECT "Status" FROM public."LabBookingStatus" WHERE "Status" = 'TechnicianVerified'
);

--------------------------------------Srilekha 20June2023
DROP FUNCTION IF EXISTS public."udf_PharmacyBills_Report"(text, integer, character varying, character varying, integer, integer, integer, timestamp without time zone, timestamp without time zone, text, integer, text);

-- FUNCTION: public.udf_PharmacyBills_Report(text, integer, character varying, character varying, integer, integer, integer, timestamp without time zone, timestamp without time zone, text, integer, text)

CREATE OR REPLACE FUNCTION public."udf_PharmacyBills_Report"(
	"billNumber" text DEFAULT NULL::text,
	"patientId" integer DEFAULT NULL::integer,
	"patientMobile" character varying DEFAULT NULL::text,
	"uMRNo" character varying DEFAULT NULL::text,
	"payTypeId" integer DEFAULT NULL::integer,
	"providerId" integer DEFAULT NULL::integer,
	"createdBy" integer DEFAULT NULL::integer,
	"fromDate" timestamp without time zone DEFAULT (now())::timestamp without time zone,
	"toDate" timestamp without time zone DEFAULT (now())::timestamp without time zone,
	"retailName" text DEFAULT NULL::text,
	"retailPharmacyId" integer DEFAULT NULL::integer,
	"locationId" text DEFAULT NULL::text)
    RETURNS TABLE("PharmacySaleHeaderId" integer, "BillNumber" character varying, "SaleDate" timestamp without time zone, "PatientName" character varying, "PatientMobile" character varying, "UMRNo" character varying, "PaidVia" character varying, "PaymentNumber" character varying, "CreatedByName" text, "RoleName" character varying, "ProviderName" character varying, "TotalAmount" numeric, "RetailName" text, "OverallTaxes" numeric, "LocationName" character varying, "TypeOfPayment" character) 
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000

AS $BODY$
BEGIN

return query

select A."PharmacySaleHeaderId" ,A."BillNumber",A."SaleDate",A."PatientName",A."Mobile" 
,A."UMRNo",A."PaidVia",A."PaymentNumber",A."CreatedByName",A."Role" ,
A."ProviderName", sum(A."Cost") as "TotalAmount"  ,A."RetailName",A."OverallTaxes",A."LocationName",
A."TypeOfPayment" from (
select PH."PharmacySaleHeaderId" ,PH."BillNumber",PH."CreatedDate" "SaleDate",PH."PatientName",PH."Mobile" 
,Pa."UMRNo",PT."PayTypeName" as "PaidVia",PH."PaymentNumber",A."FullName" 
"CreatedByName",R."RoleName" "Role" ,
PH."ProviderName", RC."Cost"  ,RP."RetailName",PH."OverallTaxes",L."Name" as "LocationName",
PH."PaymentType" as "TypeOfPayment",RC."ReceiptId"
from  "PharmacySaleHeader" PH
 join "Patient" Pa on Pa."PatientId"::text=PH."PatientId"::text
join "Account" A on A."AccountId"=PH."CreatedBy"
join "Role" R on R."RoleId"=A."RoleId"
join "PharmacySaleDetail" PSD on PSD."PharmacySaleHeaderId"=PH."PharmacySaleHeaderId"
join "PharmacyRetailStock" PRS on PRS."PharmacyRetailStockId"=PSD."PharmacyRetailStockId"
join "RetailWareHouseLink" RWL on RWL."RetailWareHouseLinkId" = PRS."RetailWareHouseLinkId"
join "RetailPharmacy" RP on RP."RetailPharmacyId"=RWL."RetailPharmacyId"
join "Location" L on L."LocationId" = PH."LocationId"
	 
left Join "Receipt" RC on RC."RespectiveId"=PH."PharmacySaleHeaderId"  and RC."ReceiptAreaTypeId"=1
left join "PayType" PT on PT."PayTypeId"=RC."PayTypeId"
where	case when "billNumber" is null then 1=1 else  PH."BillNumber" ilike '%' || "billNumber" ||'%' end and 
case when "patientId" is null then 1=1 else PH."PatientId"="patientId" end and
	
	case when "patientMobile" is null then 1=1 else  PH."Mobile" ilike '%' || "patientMobile" ||'%' end  and
	case when "uMRNo" is null then 1=1 else  Pa."UMRNo" ilike '%' || "uMRNo" ||'%' end  and
				case when "payTypeId" is null then 1=1 else  PT."PayTypeId" = "payTypeId" end  and
	case when "providerId" is null then 1=1 else  PH."ProviderId" ="providerId"  end  and
		case when "createdBy" is null then 1=1 else  A."AccountId"="createdBy" end and
 case when "fromDate" is null then 1=1 else PH."SaleDate" >= "fromDate" end and 
 case when "toDate" is null then 1=1 else PH."SaleDate" <= "toDate" end  and
 case when "retailName" is null then 1=1 else  RP."RetailName" ilike '%' || "retailName" ||'%' end and 
 	case when "retailPharmacyId" is null then 1=1 else  RP."RetailPharmacyId" = "retailPharmacyId" end and 
case when "locationId" is null then 1=1 else PH."LocationId" = "locationId"::int end
group by PH."PharmacySaleHeaderId" ,PH."BillNumber",PH."SaleDate", PH."OverallNetAmount",PH."PatientName",PH."Mobile",Pa."UMRNo",PT."PayTypeName"
, PH."PaymentNumber", A."FullName" 
,R."RoleName" ,PH."ProviderName",RP."RetailName",PH."OverallTaxes",L."Name",RC."ReceiptId" ) A
group by A."PharmacySaleHeaderId" ,A."BillNumber",A."SaleDate",A."PatientName",A."Mobile" 
,A."UMRNo",A."PaidVia",A."PaymentNumber",A."CreatedByName",A."Role" ,
A."ProviderName"  ,A."RetailName",A."OverallTaxes",A."LocationName",
A."TypeOfPayment",A."ReceiptId"
order by A."SaleDate" desc;
END
$BODY$;

ALTER FUNCTION public."udf_PharmacyBills_Report"(text, integer, character varying, character varying, integer, integer, integer, timestamp without time zone, timestamp without time zone, text, integer, text)
    OWNER TO postgres;
--------------------------JayShreev 20June2023
alter table if exists "MasterBill"
drop constraint if exists  "FK_Receipt_ModulesMasterId";

alter table if exists "MasterBill"
add column if not exists "LocationId" integer null;
alter table if exists "MasterBill"
add column if not exists "ReceiptAreaTypeId" integer null;

-----------------------------------------------------------------------------------------
DROP FUNCTION IF EXISTS public."Masterbills_AppointmentReports"(date, date, integer, integer);

CREATE OR REPLACE FUNCTION public."Masterbills_AppointmentReports"(
	"fromDate" date DEFAULT NULL::date,
	"toDate" date DEFAULT NULL::date,
	locationid integer DEFAULT NULL::integer,
	moduleid integer DEFAULT NULL::integer)
    RETURNS TABLE("BillNumber" character varying, "BillDate" timestamp without time zone, "BillStatusTypeId" integer, "BillStatus" character varying, "Total" numeric, "Discount" numeric, "NetTotal" numeric,"Rounding" numeric, "Receipts" text, "Receipts_Cost" text, "ReceiptSum" numeric, "ReceiptAreaTypeId" integer, "PatientName" text, "Mobile" character varying, "UMRNo" character varying, "ProviderName" character varying, "LocationId" integer, "ModuleName" character varying, "LocationName" character varying, "AppointmentNo" character varying, "AppointmentDate" timestamp without time zone,"OPConsultation" numeric,"ScanConsultation" numeric,"Lab" numeric,"Pharmacy" numeric,"RegistrationCharges" numeric) 
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000

AS $BODY$
begin
return query

with getreceipts as (
	select  MB."MasterBillId",MB."BillNumber",string_agg(R."ReceiptId"::text,',')   AS "Receipts",
string_agg(R."Cost"::text,',')  AS "Receipts_Cost",MB."ReceiptAreaTypeId",--MB."ModulesMasterId",
	sum(R."Cost") as "ReceiptSum"
	from "MasterBill" MB 
	 join  "Receipt" R on R."MasterBillId"=MB."MasterBillId"	
	group by (MB."MasterBillId")
	--order by MB."BillNumber" asc
)
,appointment as(
select 
	distinct on (MB."MasterBillId")
 MB."BillNumber",MB."MasterBillId",MB."BillDate",MB."BillStatusTypeId",BST."Name" as "BillStatus",
MB."Total",MB."Discount",MB."NetTotal",MB."Rounding",--GR."Receipts",GR."Receipts_Cost",GR."ReceiptSum",
P."FullName" as "PatientName",P."Mobile",P."UMRNo",pr."FullName" as "ProviderName",
AT."LocationId",MM."Name" as "ModuleName",L."Name" as "LocationName",
AP."AppointmentNo",AP."AppointmentDate"
FROM "MasterBill" MB
 Join "Appointment" AP on AP."AppointmentId"=MB."ModuleId"
	join "Provider" pr on pr."ProviderId"= AP."ProviderId"
 join "BillStatusType" BST on BST."BillStatusTypeId"=MB."BillStatusTypeId"
 join "Patient" P on P."PatientId"=MB."PatientId"
 --join "ModulesMaster" MM on MM."ModulesMasterId"=MB."ModulesMasterId"	
join "ReceiptAreaType" MM on MM."ReceiptAreaTypeId"=MB."ReceiptAreaTypeId"	
 join "AppointmentTransaction" AT on AT."AppointmentId"=AP."AppointmentId"-- and MB."ReceiptAreaTypeId"=4
 join "Location" L on L."LocationId"=AT."LocationId"	
where  
case when "fromDate" is null then 1=1 else "fromDate"<= AP."AppointmentDate"::date end 
 		and case when "toDate" is null then 1=1 else AP."AppointmentDate"::date<=  "toDate" end 
		 and case when "locationid" is null then 1=1 else AT."LocationId" = "locationid" end
)
,lab as (
SELECT distinct on (MB."MasterBillId")
MB."BillNumber",MB."MasterBillId",MB."BillDate",MB."BillStatusTypeId",BST."Name" as "BillStatus",
MB."Total",MB."Discount",MB."NetTotal",MB."Rounding",--GR."Receipts",GR."Receipts_Cost",GR."ReceiptSum",
P."FullName" as "PatientName",P."Mobile",P."UMRNo",prv."FullName" as "ProviderName",
	L."Name" as "LocationName",nlbh."LocationId",MM."Name" as "ModuleName",
 nlbh."RequisitionNumber" as "AppointmentNo",nlbh."CreatedDate" as "AppointmentDate"
FROM "MasterBill" MB
			join "NewLabBookingHeader" nlbh on nlbh."NewLabBookingHeaderId"=MB."ModuleId"
			join "Provider" prv on prv."ProviderId" = nlbh."DoctorId"    
			join "BillStatusType" BST on BST."BillStatusTypeId"=MB."BillStatusTypeId"                                                                   
			join "Patient" P on P."PatientId"=MB."PatientId"
			--join "ModulesMaster" MM on MM."ModulesMasterId"=MB."ModulesMasterId"   
	join "ReceiptAreaType" MM on MM."ReceiptAreaTypeId"=MB."ReceiptAreaTypeId"	
			-- join "getreceipts" GR on GR."MasterBillId"=MB."MasterBillId"
 			join "AppointmentTransaction" AT on AT."AppointmentId"=nlbh."NewLabBookingHeaderId"
		    join "Location" L on L."LocationId"=AT."LocationId"
		where 	
	case when "fromDate" is null then 1=1 else "fromDate"<= nlbh."CreatedDate"::date end 
 		and case when "toDate" is null then 1=1 else nlbh."CreatedDate"::date<=  "toDate" end 
		 and case when "locationid" is null then 1=1 else AT."LocationId" = "locationid" end																		  								   
)
,pharma as (
SELECT distinct on (MB."MasterBillId")
MB."BillNumber",MB."MasterBillId",MB."BillDate",MB."BillStatusTypeId",BST."Name" as "BillStatus",
MB."Total",MB."Discount",MB."NetTotal",MB."Rounding",--GR."Receipts",GR."Receipts_Cost",GR."ReceiptSum",
P."FullName" as "PatientName",P."Mobile",P."UMRNo",nlbh."ProviderName",
	L."Name" as "LocationName",nlbh."LocationId",MM."Name" as "ModuleName",
 nlbh."BillNumber" as "AppointmentNo",nlbh."CreatedDate" as "AppointmentDate"		
	FROM "MasterBill" MB
			join "PharmacySaleHeader" nlbh on nlbh."PharmacySaleHeaderId"=MB."ModuleId"                               
			join "BillStatusType" BST on BST."BillStatusTypeId"=MB."BillStatusTypeId"                                                                   
			join "Patient" P on P."PatientId"=MB."PatientId"
			--join "ModulesMaster" MM on MM."ModulesMasterId"=MB."ModulesMasterId" 
	join "ReceiptAreaType" MM on MM."ReceiptAreaTypeId"=MB."ReceiptAreaTypeId"	
			-- join "getreceipts" GR on GR."MasterBillId"=MB."MasterBillId"
 			join "AppointmentTransaction" AT on AT."AppointmentId"=nlbh."PharmacySaleHeaderId"
			join "Location" L on L."LocationId"=AT."LocationId"
	where 
		case when "fromDate" is null then 1=1 else "fromDate"<= nlbh."CreatedDate"::date end 
 		and case when "toDate" is null then 1=1 else nlbh."CreatedDate"::date<=  "toDate" end 
		 and case when "locationid" is null then 1=1 else AT."LocationId" = "locationid" end																		  								   
)
,scan as(
SELECT distinct on (MB."MasterBillId")
MB."BillNumber",MB."MasterBillId",MB."BillDate",MB."BillStatusTypeId",BST."Name" as "BillStatus",
MB."Total",MB."Discount",MB."NetTotal",MB."Rounding",--GR."Receipts",GR."Receipts_Cost",GR."ReceiptSum",
P."FullName" as "PatientName",P."Mobile",P."UMRNo",SM."MachineName" as "ProviderName",
	L."Name" as "LocationName",nlbh."LocationId",MM."Name" as "ModuleName",
 nlbh."RequisitionNumber" as "AppointmentNo",nlbh."AppointmentDate"			
	FROM "MasterBill" MB
			join "BookScanAppointment" nlbh on nlbh."BookScanAppointmentId"=MB."ModuleId" 
			join "ScanMachineMaster" SM on SM."ScanMachineMasterId"=nlbh."ScanMachineMasterId"
			join "BillStatusType" BST on BST."BillStatusTypeId"=MB."BillStatusTypeId"                                                                   
			join "Patient" P on P."PatientId"=MB."PatientId"
			--join "ModulesMaster" MM on MM."ModulesMasterId"=MB."ModulesMasterId"  
	join "ReceiptAreaType" MM on MM."ReceiptAreaTypeId"=MB."ReceiptAreaTypeId"	
			-- join "getreceipts" GR on GR."MasterBillId"=MB."MasterBillId"
 			join "AppointmentTransaction" AT on AT."AppointmentId"=nlbh."BookScanAppointmentId"
		    join "Location" L on L."LocationId"=AT."LocationId"
	where
		case when "fromDate" is null then 1=1 else "fromDate"<= nlbh."AppointmentDate"::date end 
 		and case when "toDate" is null then 1=1 else nlbh."AppointmentDate"::date<=  "toDate" end 
		 and case when "locationid" is null then 1=1 else AT."LocationId" = "locationid" end	
)

SELECT O."BillNumber",O."BillDate",O."BillStatusTypeId",O."BillStatus",
O."Total",O."Discount",O."NetTotal",O."Rounding",O."Receipts",O."Receipts_Cost",O."ReceiptSum",O."ReceiptAreaTypeId",
O."PatientName",O."Mobile",O."UMRNo",O."ProviderName",
O."LocationId",O."ModuleName",O."LocationName",
O."AppointmentNo",O."AppointmentDate",
coalesce(case when O."ReceiptAreaTypeId"=4 then O."ReceiptSum" end,0) as "OPConsultation" ,
coalesce(case when O."ReceiptAreaTypeId"=10 then O."ReceiptSum" end,0) as "ScanConsultation",
coalesce(case when O."ReceiptAreaTypeId"=8 then O."ReceiptSum" end,0) as "Lab" ,
coalesce(case when O."ReceiptAreaTypeId"=1 then O."ReceiptSum" end,0) as "Pharmacy",
coalesce(case when O."ReceiptAreaTypeId"=3 then O."ReceiptSum" end,0) as "RegistrationCharges"
from 
(
	Select  AP."BillNumber",AP."BillDate",AP."BillStatusTypeId",AP."BillStatus",
AP."Total",AP."Discount",AP."NetTotal",AP."Rounding",GR."Receipts",GR."Receipts_Cost",GR."ReceiptSum",GR."ReceiptAreaTypeId",
AP."PatientName",AP."Mobile",AP."UMRNo",AP."ProviderName",
AP."LocationId",AP."ModuleName",AP."LocationName",
AP."AppointmentNo",AP."AppointmentDate"
from getreceipts GR
join "appointment" AP on GR."MasterBillId"=AP."MasterBillId"	
UNION
	Select  AP."BillNumber",AP."BillDate",AP."BillStatusTypeId",AP."BillStatus",
AP."Total",AP."Discount",AP."NetTotal",AP."Rounding",GR."Receipts",GR."Receipts_Cost",GR."ReceiptSum",GR."ReceiptAreaTypeId",
AP."PatientName",AP."Mobile",AP."UMRNo",AP."ProviderName",
AP."LocationId",AP."ModuleName",AP."LocationName",
AP."AppointmentNo",AP."AppointmentDate"
from getreceipts GR
join "lab" AP on GR."MasterBillId"=AP."MasterBillId"
	
	UNION
	Select  AP."BillNumber",AP."BillDate",AP."BillStatusTypeId",AP."BillStatus",
AP."Total",AP."Discount",AP."NetTotal",AP."Rounding",GR."Receipts",GR."Receipts_Cost",GR."ReceiptSum",GR."ReceiptAreaTypeId",
AP."PatientName",AP."Mobile",AP."UMRNo",AP."ProviderName",
AP."LocationId",AP."ModuleName",AP."LocationName",
AP."AppointmentNo",AP."AppointmentDate"
from getreceipts GR
join "pharma" AP on GR."MasterBillId"=AP."MasterBillId"
	UNION
	Select  AP."BillNumber",AP."BillDate",AP."BillStatusTypeId",AP."BillStatus",
AP."Total",AP."Discount",AP."NetTotal",AP."Rounding",GR."Receipts",GR."Receipts_Cost",GR."ReceiptSum",GR."ReceiptAreaTypeId",
AP."PatientName",AP."Mobile",AP."UMRNo",AP."ProviderName",
AP."LocationId",AP."ModuleName",AP."LocationName",
AP."AppointmentNo",AP."AppointmentDate"
from getreceipts GR
join "scan" AP on GR."MasterBillId"=AP."MasterBillId"
		
)O
where 	
	 case when "moduleid" is null then 1=1 else O."ReceiptAreaTypeId" = "moduleid" end	
	 
GROUP BY GROUPING SETS((O."BillNumber",O."BillDate",O."BillStatusTypeId",O."BillStatus",
O."Total",O."Discount",O."NetTotal",O."Rounding",O."Receipts",O."Receipts_Cost",O."ReceiptSum",O."ReceiptAreaTypeId",
O."PatientName",O."Mobile",O."UMRNo",O."ProviderName",
O."LocationId",O."ModuleName",O."LocationName",
O."AppointmentNo",O."AppointmentDate")) 

order by O."ModuleName" asc;

end
$BODY$;

ALTER FUNCTION public."Masterbills_AppointmentReports"(date, date, integer, integer)
    OWNER TO postgres;

------------------srilekha 21 June 2023

alter table if exists "MasterBill" 
drop column if exists "ModulesMasterId"; 

---------------------------shiva kumar 21June 2023

 create table If not exists "DietSlots"(
    "DietSlotId" serial primary key,
    "Name" character varying,
    "StartTime" time without time zone NOT NULL,
    "EndTime" time without time zone NOT NULL,
    "Active" boolean,
    "CreatedBy" integer NOT NULL references "Account" ("AccountId"),
    "CreatedDate" timestamp without time zone NOT NULL,
    "ModifiedBy" integer references "Account" ("AccountId"),
    "ModifiedDate" timestamp without time zone,
    "LocationId" integer references "Location"("LocationId")
);

----------------------------jayshreee 21June 2023
DROP FUNCTION IF EXISTS public."Masterbills_AppointmentReports"(date, date, integer, integer,integer );

CREATE OR REPLACE FUNCTION public."Masterbills_AppointmentReports"(
	"fromDate" date DEFAULT NULL::date,
	"toDate" date DEFAULT NULL::date,
	locationid integer DEFAULT NULL::integer,
	moduleid integer DEFAULT NULL::integer,
patientid integer DEFAULT NULL::integer)
    RETURNS TABLE("BillNumber" character varying, "BillDate" timestamp without time zone, "BillStatusTypeId" integer,
				  "BillStatus" character varying, "Total" numeric, "Discount" numeric, "NetTotal" numeric, 
				  "Rounding" numeric, "Receipts" text, "Receipts_Cost" text, "ReceiptSum" numeric,
				  "ReceiptAreaTypeId" integer, "PatientName" text, "Mobile" character varying,
				  "UMRNo" character varying, "ProviderName" character varying, "LocationId" integer,
				   "LocationName" character varying,"PatientId" integer,"ModuleName" character varying,
				  "AppointmentNo" character varying, "AppointmentDate" timestamp without time zone, "OPConsultation" numeric, "ScanConsultation" numeric, "Lab" numeric, "Pharmacy" numeric, "RegistrationCharges" numeric) 
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000

AS $BODY$
begin
return query

with getreceipts as (
	select  MB."MasterBillId",MB."BillNumber",string_agg(R."ReceiptId"::text,',')   AS "Receipts",
string_agg(R."Cost"::text,',')  AS "Receipts_Cost",MB."ReceiptAreaTypeId",MB."LocationId",L."Name" as "LocationName",
	MB."PatientId",
sum(R."Cost") as "ReceiptSum"
	from "MasterBill" MB 
	 join  "Receipt" R on R."MasterBillId"=MB."MasterBillId"	
	left join "Location" L on L."LocationId"=MB."LocationId"
	join "Patient" P on P."PatientId"=MB."PatientId"
		group by (MB."MasterBillId",L."Name")
	--order by MB."BillNumber" asc
)
,appointment as(
select 
	distinct on (MB."MasterBillId")
 MB."BillNumber",MB."MasterBillId",MB."BillDate",MB."BillStatusTypeId",BST."Name" as "BillStatus",
MB."Total",MB."Discount",MB."NetTotal",MB."Rounding",--GR."Receipts",GR."Receipts_Cost",GR."ReceiptSum",
P."FullName" as "PatientName",P."Mobile",P."UMRNo",pr."FullName" as "ProviderName",
--AT."LocationId",L."Name" as "LocationName",
	MM."Name" as "ModuleName",
AP."AppointmentNo",AP."AppointmentDate"
FROM "MasterBill" MB
 Join "Appointment" AP on AP."AppointmentId"=MB."ModuleId"
	join "Provider" pr on pr."ProviderId"= AP."ProviderId"
 join "BillStatusType" BST on BST."BillStatusTypeId"=MB."BillStatusTypeId"
 join "Patient" P on P."PatientId"=MB."PatientId"
 --join "ModulesMaster" MM on MM."ModulesMasterId"=MB."ModulesMasterId"	
join "ReceiptAreaType" MM on MM."ReceiptAreaTypeId"=MB."ReceiptAreaTypeId"	
 join "AppointmentTransaction" AT on AT."AppointmentId"=AP."AppointmentId"-- and MB."ReceiptAreaTypeId"=4
 --join "Location" L on L."LocationId"=AT."LocationId"	
where  
case when "fromDate" is null then 1=1 else "fromDate"<= AP."AppointmentDate"::date end 
 		and case when "toDate" is null then 1=1 else AP."AppointmentDate"::date<=  "toDate" end 
		-- and case when "locationid" is null then 1=1 else AT."LocationId" = "locationid" end
)
,lab as (
SELECT distinct on (MB."MasterBillId")
MB."BillNumber",MB."MasterBillId",MB."BillDate",MB."BillStatusTypeId",BST."Name" as "BillStatus",
MB."Total",MB."Discount",MB."NetTotal",MB."Rounding",--GR."Receipts",GR."Receipts_Cost",GR."ReceiptSum",
P."FullName" as "PatientName",P."Mobile",P."UMRNo",prv."FullName" as "ProviderName",
--	L."Name" as "LocationName",nlbh."LocationId",
	MM."Name" as "ModuleName",
 nlbh."RequisitionNumber" as "AppointmentNo",nlbh."CreatedDate" as "AppointmentDate"
FROM "MasterBill" MB
			join "NewLabBookingHeader" nlbh on nlbh."NewLabBookingHeaderId"=MB."ModuleId"
			join "Provider" prv on prv."ProviderId" = nlbh."DoctorId"    
			join "BillStatusType" BST on BST."BillStatusTypeId"=MB."BillStatusTypeId"                                                                   
			join "Patient" P on P."PatientId"=MB."PatientId"
			--join "ModulesMaster" MM on MM."ModulesMasterId"=MB."ModulesMasterId"   
	join "ReceiptAreaType" MM on MM."ReceiptAreaTypeId"=MB."ReceiptAreaTypeId"	
			-- join "getreceipts" GR on GR."MasterBillId"=MB."MasterBillId"
 			join "AppointmentTransaction" AT on AT."AppointmentId"=nlbh."NewLabBookingHeaderId"
		   -- join "Location" L on L."LocationId"=AT."LocationId"
		where 	
	case when "fromDate" is null then 1=1 else "fromDate"<= nlbh."CreatedDate"::date end 
 		and case when "toDate" is null then 1=1 else nlbh."CreatedDate"::date<=  "toDate" end 
		-- and case when "locationid" is null then 1=1 else AT."LocationId" = "locationid" end																		  								   
)
,pharma as (
SELECT distinct on (MB."MasterBillId")
MB."BillNumber",MB."MasterBillId",MB."BillDate",MB."BillStatusTypeId",BST."Name" as "BillStatus",
MB."Total",MB."Discount",MB."NetTotal",MB."Rounding",--GR."Receipts",GR."Receipts_Cost",GR."ReceiptSum",
P."FullName" as "PatientName",P."Mobile",P."UMRNo",nlbh."ProviderName",
	--L."Name" as "LocationName",nlbh."LocationId",
	MM."Name" as "ModuleName",
 nlbh."BillNumber" as "AppointmentNo",nlbh."CreatedDate" as "AppointmentDate"		
	FROM "MasterBill" MB
			join "PharmacySaleHeader" nlbh on nlbh."PharmacySaleHeaderId"=MB."ModuleId"                               
			join "BillStatusType" BST on BST."BillStatusTypeId"=MB."BillStatusTypeId"                                                                   
			join "Patient" P on P."PatientId"=MB."PatientId"
			--join "ModulesMaster" MM on MM."ModulesMasterId"=MB."ModulesMasterId" 
	join "ReceiptAreaType" MM on MM."ReceiptAreaTypeId"=MB."ReceiptAreaTypeId"	
			-- join "getreceipts" GR on GR."MasterBillId"=MB."MasterBillId"
 			join "AppointmentTransaction" AT on AT."AppointmentId"=nlbh."PharmacySaleHeaderId"
			--join "Location" L on L."LocationId"=AT."LocationId"
	where 
		case when "fromDate" is null then 1=1 else "fromDate"<= nlbh."CreatedDate"::date end 
 		and case when "toDate" is null then 1=1 else nlbh."CreatedDate"::date<=  "toDate" end 
		-- and case when "locationid" is null then 1=1 else AT."LocationId" = "locationid" end																		  								   
)
,scan as(
SELECT distinct on (MB."MasterBillId")
MB."BillNumber",MB."MasterBillId",MB."BillDate",MB."BillStatusTypeId",BST."Name" as "BillStatus",
MB."Total",MB."Discount",MB."NetTotal",MB."Rounding",--GR."Receipts",GR."Receipts_Cost",GR."ReceiptSum",
P."FullName" as "PatientName",P."Mobile",P."UMRNo",SM."MachineName" as "ProviderName",
	--L."Name" as "LocationName",nlbh."LocationId",
	MM."Name" as "ModuleName",
 nlbh."RequisitionNumber" as "AppointmentNo",nlbh."AppointmentDate"			
	FROM "MasterBill" MB
			join "BookScanAppointment" nlbh on nlbh."BookScanAppointmentId"=MB."ModuleId" 
			join "ScanMachineMaster" SM on SM."ScanMachineMasterId"=nlbh."ScanMachineMasterId"
			join "BillStatusType" BST on BST."BillStatusTypeId"=MB."BillStatusTypeId"                                                                   
			join "Patient" P on P."PatientId"=MB."PatientId"
			--join "ModulesMaster" MM on MM."ModulesMasterId"=MB."ModulesMasterId"  
	join "ReceiptAreaType" MM on MM."ReceiptAreaTypeId"=MB."ReceiptAreaTypeId"	
			-- join "getreceipts" GR on GR."MasterBillId"=MB."MasterBillId"
 			join "AppointmentTransaction" AT on AT."AppointmentId"=nlbh."BookScanAppointmentId"
		    --join "Location" L on L."LocationId"=AT."LocationId"
	where
		case when "fromDate" is null then 1=1 else "fromDate"<= nlbh."AppointmentDate"::date end 
 		and case when "toDate" is null then 1=1 else nlbh."AppointmentDate"::date<=  "toDate" end 
		-- and case when "locationid" is null then 1=1 else AT."LocationId" = "locationid" end	
)

SELECT O."BillNumber",O."BillDate",O."BillStatusTypeId",O."BillStatus",
O."Total",O."Discount",O."NetTotal",O."Rounding",O."Receipts",O."Receipts_Cost",O."ReceiptSum",O."ReceiptAreaTypeId",
O."PatientName",O."Mobile",O."UMRNo",O."ProviderName",
O."LocationId",O."LocationName",O."PatientId",
O."ModuleName",
O."AppointmentNo",O."AppointmentDate",
coalesce(case when O."ReceiptAreaTypeId"=4 then O."ReceiptSum" end,0) as "OPConsultation" ,
coalesce(case when O."ReceiptAreaTypeId"=10 then O."ReceiptSum" end,0) as "ScanConsultation",
coalesce(case when O."ReceiptAreaTypeId"=8 then O."ReceiptSum" end,0) as "Lab" ,
coalesce(case when O."ReceiptAreaTypeId"=1 then O."ReceiptSum" end,0) as "Pharmacy",
coalesce(case when O."ReceiptAreaTypeId"=3 then O."ReceiptSum" end,0) as "RegistrationCharges"
from 
(
	Select  AP."BillNumber",AP."BillDate",AP."BillStatusTypeId",AP."BillStatus",
AP."Total",AP."Discount",AP."NetTotal",AP."Rounding",GR."Receipts",GR."Receipts_Cost",GR."ReceiptSum",GR."ReceiptAreaTypeId",
AP."PatientName",AP."Mobile",AP."UMRNo",AP."ProviderName",
GR."LocationId",GR."LocationName",GR."PatientId",
	AP."ModuleName",
AP."AppointmentNo",AP."AppointmentDate"
from getreceipts GR
join "appointment" AP on GR."MasterBillId"=AP."MasterBillId"	
UNION
	Select  AP."BillNumber",AP."BillDate",AP."BillStatusTypeId",AP."BillStatus",
AP."Total",AP."Discount",AP."NetTotal",AP."Rounding",GR."Receipts",GR."Receipts_Cost",GR."ReceiptSum",GR."ReceiptAreaTypeId",
AP."PatientName",AP."Mobile",AP."UMRNo",AP."ProviderName",
GR."LocationId",GR."LocationName",GR."PatientId",
	AP."ModuleName",
AP."AppointmentNo",AP."AppointmentDate"
from getreceipts GR
join "lab" AP on GR."MasterBillId"=AP."MasterBillId"
	
	UNION
	Select  AP."BillNumber",AP."BillDate",AP."BillStatusTypeId",AP."BillStatus",
AP."Total",AP."Discount",AP."NetTotal",AP."Rounding",GR."Receipts",GR."Receipts_Cost",GR."ReceiptSum",GR."ReceiptAreaTypeId",
AP."PatientName",AP."Mobile",AP."UMRNo",AP."ProviderName",
GR."LocationId",GR."LocationName",GR."PatientId",
	AP."ModuleName",
AP."AppointmentNo",AP."AppointmentDate"
from getreceipts GR
join "pharma" AP on GR."MasterBillId"=AP."MasterBillId"
	UNION
	Select  AP."BillNumber",AP."BillDate",AP."BillStatusTypeId",AP."BillStatus",
AP."Total",AP."Discount",AP."NetTotal",AP."Rounding",GR."Receipts",GR."Receipts_Cost",GR."ReceiptSum",GR."ReceiptAreaTypeId",
AP."PatientName",AP."Mobile",AP."UMRNo",AP."ProviderName",
GR."LocationId",GR."LocationName",GR."PatientId",
	AP."ModuleName",
AP."AppointmentNo",AP."AppointmentDate"
from getreceipts GR
join "scan" AP on GR."MasterBillId"=AP."MasterBillId"
		
)O
where 	
	 case when "moduleid" is null then 1=1 else O."ReceiptAreaTypeId" = "moduleid" end	
	 and case when "locationid" is null then 1=1 else O."LocationId" = "locationid" end	
	 and case when "patientid" is null then 1=1 else O."PatientId" = "patientid" end	
	 
GROUP BY GROUPING SETS((O."BillNumber",O."BillDate",O."BillStatusTypeId",O."BillStatus",
O."Total",O."Discount",O."NetTotal",O."Rounding",O."Receipts",O."Receipts_Cost",O."ReceiptSum",O."ReceiptAreaTypeId",
O."PatientName",O."Mobile",O."UMRNo",O."ProviderName",
O."LocationId",O."ModuleName",O."LocationName",O."PatientId",
O."AppointmentNo",O."AppointmentDate")) 

order by O."ModuleName" asc;

end
$BODY$;

--------------------------------------mounika Akula 21June 2023
-- FUNCTION: public.widget_GetSampleRecievedCount()

DROP FUNCTION if exists public."widget_GetSampleRecievedCount"();

CREATE OR REPLACE FUNCTION public."widget_GetSampleRecievedCount"(
	"fromDate" date DEFAULT NULL::date)
    RETURNS TABLE("Count" bigint) 
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000

AS $BODY$
begin
return query
select count(*) from "LabBookingTimeLine" lbt
	join "LabBookingStatus" lbs on lbs."LabBookingStatusId" = lbt."LabBookingStatusId" where lbs."Status" = 'SampleRecieved'
	and lbt."CreatedDate" :: date ="fromDate";
end
$BODY$;

ALTER FUNCTION public."widget_GetSampleRecievedCount"(date)
    OWNER TO postgres;
-------------------------------------------------------
 DROP FUNCTION if exists public."widget_GetVerifiedCount"();

CREATE OR REPLACE FUNCTION public."widget_GetVerifiedCount"(
	"fromDate" date DEFAULT NULL::date)
    RETURNS TABLE("Count" bigint) 
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000

AS $BODY$
begin
return query
select count(*) from "LabBookingTimeLine" lbt
	join "LabBookingStatus" lbs on lbs."LabBookingStatusId" = lbt."LabBookingStatusId" where lbs."Status" = 'Verified'
	and lbt."CreatedDate" :: date ="fromDate";
end
$BODY$;

ALTER FUNCTION public."widget_GetVerifiedCount"(date)
    OWNER TO postgres;
------------------------------------------------------------
 DROP FUNCTION if exists public."widget_GetTransferCount"();

CREATE OR REPLACE FUNCTION public."widget_GetTransferCount"(
	"fromDate" date DEFAULT NULL::date)
    RETURNS TABLE("Count" bigint) 
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000

AS $BODY$
begin
return query
select COUNT(*) from "LabTransferHeader" LT
	join "LabTransferDetail" LD on LD."LabTransferHeaderId"=LT."LabTransferHeaderId"
	join "Account" A on A."AccountId" = LT."TransferedBy"
	where LT."TransferedDate"::date="fromDate";
end
$BODY$;

ALTER FUNCTION public."widget_GetTransferCount"(date)
    OWNER TO postgres;
------------------------------
-- FUNCTION: public.widget_GetCanceledCount()
 DROP FUNCTION if exists public."widget_GetCanceledCount"();
CREATE OR REPLACE FUNCTION public."widget_GetCanceledCount"(
	"fromDate" date DEFAULT NULL::date,
      "referenceId" integer DEFAULT NULL::integer,
	"locationId" integer DEFAULT NULL::integer )
    RETURNS TABLE("Count" bigint) 
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000

AS $BODY$
begin
return query

select COUNT(*)
 from "NewLabBookingHeader" LH
 join "NewLabBookingDetail" LD on LD."NewLabBookingHeaderId"=LH."NewLabBookingHeaderId"
  join "Provider" pr on pr."ProviderId"= LH."DoctorId"
	where LH."CreatedDate"::date="fromDate" and  LD."LabBookingStatusId"=2 ;
end
$BODY$;

ALTER FUNCTION public."widget_GetCanceledCount"(date,integer,integer)
    OWNER TO postgres;
---------------------------------------
-- FUNCTION: public.widget_GetSampleCount()

DROP FUNCTION if exists public."widget_GetSampleCount"();
CREATE OR REPLACE FUNCTION public."widget_GetSampleCount"(
	"fromDate" date DEFAULT NULL::date,
      "referenceId" integer DEFAULT NULL::integer,
	"locationId" integer DEFAULT NULL::integer   )
    RETURNS TABLE("Count" bigint) 
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000

AS $BODY$
begin
return query
select COUNT(*) from "LabSampleCollection" LS
 join "NewLabBookingDetail" LD on LD."NewLabBookingDetailId"=LS."NewLabBookingDetailId"
 join "Account" A on A."AccountId"=LS."SampleCollectedBy"
 where LS."CollectionDate"::date="fromDate"
 and case when "locationId" is null then 1=1 else LS."LocationId"= "locationId" end;
 end;
$BODY$;

ALTER FUNCTION public."widget_GetSampleCount"(date,int,int)
    OWNER TO postgres;

---------------------------------Shivani 21June 2023
alter table IF EXISTS "ObEncounter" 
add COLUMN IF NOT EXISTS "RefferalOrder" text;
 -------------------------------Srilekha 21June 2023
alter table IF EXISTS "NewLabBookingHeader"
add column IF NOT EXISTS "PaymentType" character(1);

----------Shivani 21June2023
alter table IF EXISTS "ObEncounter" 
add COLUMN IF NOT EXISTS "ANCCardGenerationId" int;
----------Chandana 21June2023
alter table IF EXISTS "Appointment" 
add column IF NOT EXISTS "IsEmergency" boolean;
---------------------------------Manish 21June2023
create table if not exists "LabSampleCollectionDetail" (
				"LabSampleCollectionDetailId" serial primary Key,
				"LabSampleCollectionId" int references "LabSampleCollection"("LabSampleCollectionId"),
				"SubSampleCollectedBy" int  REFERENCES public."Account"("AccountId"),
				"SubCollectionDate" timestamp NULL,
				"SubIsBarcodeGenerated" bool NULL DEFAULT false,
				"SubBarcodeGeneratedBy" int REFERENCES public."Account"("AccountId"),
				"SubBarcodeDate" timestamp NULL,
				"LocationId" int4 NULL,
				CONSTRAINT "LabSampleCollection_LocationId_fkey" FOREIGN KEY ("LocationId") REFERENCES public."Location"("LocationId")				
);

alter table if exists "LabSampleCollectionDetail" 
add column if not exists "SampleName" text;
alter table if exists"LabSampleCollectionDetail" 
add column if not exists "LabBookingStatusId" int references "LabBookingStatus"("LabBookingStatusId");

alter table if exists "LabTransferDetail" 
add column if not exists "LabSampleCollectionDetailId" int references "LabSampleCollectionDetail"("LabSampleCollectionDetailId");
-------------------------------------------------shivani22june2023---------------------------------------------------------------------------------------------------------
alter table IF EXISTS "ObEncounter" 
add COLUMN IF NOT EXISTS "AdmissionSlip" text;

alter table IF EXISTS "ObEncounter" 
add COLUMN IF NOT EXISTS "RefferalOrder" text;
----------------------------------------------------Manish22June2023
alter table if exists "LabSampleCollectionDetail" 
add column if not exists "Comment" text;
----------------------------------------------------ShivaRam22june2023
create table if not exists "QuantityMeasure"("MeasureId" serial primary key,"MeasureName" character varying);
create table if not exists "DietItems"(
    "DietItemsId" serial primary key,
    "DietItemsName" character varying  NOT NULL,
    "Active" boolean,
    "CreatedBy" integer NOT NULL references "Account" ("AccountId"),
    "CreatedDate" timestamp without time zone NOT NULL,
    "ModifiedBy" integer references "Account" ("AccountId"),
    "ModifiedDate" timestamp without time zone,
    "MeasureId" integer not null references "QuantityMeasure"("MeasureId")
);

-------------------------------------------------shivani 26June2023
alter table IF EXISTS "ObEncounter" 
add COLUMN IF NOT EXISTS "MotherWithEpilepsy" text;
------------------------
alter table IF EXISTS "ObEncounter" 
add COLUMN IF NOT EXISTS "ExternalCephalicVersion" text;
alter table IF EXISTS "ObEncounter" 
 add COLUMN IF NOT EXISTS "DischargeSummary" text;
-------------------------------------------------Chandana 26June2023
alter table if exists "ObEncounter" 
add column if not exists "OPManagement" text;
alter table if exists "obEncounter" 
add column if not exists "Syndromes" text;
--------------------------------------------------Radhika 28June2023
alter table IF EXISTS "GynEncounter"
add column IF NOT EXISTS "GyneacAdmissionSheet" text;
alter table IF EXISTS "GynEncounter"
add column IF NOT EXISTS "GyneacSurgery" text;
alter table IF EXISTS "GynEncounter"
add column IF NOT EXISTS "GyneacDiscargeSummary" text;
---------------------------------------------------Tej 28June2023
-- FUNCTION: public.udf_FetchDoctor_With_Availability_Specialization_Op(character varying, integer, integer, character varying)

DROP FUNCTION IF EXISTS public."udf_FetchDoctor_With_Availability_Specialization_Op"(character varying, integer, integer, character varying);

CREATE OR REPLACE FUNCTION public."udf_FetchDoctor_With_Availability_Specialization_Op"(
	filter character varying DEFAULT NULL::text,
	"locationId" integer DEFAULT NULL::integer,
	"consultationTypeId" integer DEFAULT NULL::integer,
	"appointmentDate" character varying DEFAULT NULL::text)
    RETURNS TABLE("ProviderAvailabilityId" integer, "FullName" character varying, "DepartmentName" character varying, "DepartmentId" integer, "ProviderId" integer, "SpecializationId" integer, "SpecializationName" character varying, "LocationId" integer, "ConsultationTypeId" integer, "ProviderSpecializationId" text) 
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000

AS $BODY$
BEGIN

return query

SELECT DISTINCT  on (pr2."ProviderId", s."SpecializationId") prl."ProviderAvailabilityId" ,pr2."FullName" 
, d."DepartmentName" , d."DepartmentId" 
,pr2."ProviderId"
, s. "SpecializationId", s."SpecializationName"
, CMT."LocationId", prl."ConsultationTypeId",  pr2."ProviderId" || ',' || s."SpecializationId" AS "ProviderSpecializationId"
                           FROM "ProviderAvailability" prl
						  left Join "DoctorSpecializationMap" LSM on LSM."ProviderId" = prl."ProviderId"  and LSM."SpecializationId" = 																				prl."SpecializationId" and LSM."ConsultationTypeId" = prl."ConsultationTypeId"
						  left join "DoctorSpecializationChargeModuleDetails" DSCD on DSCD."ReferenceId" = LSM."DoctorSpecializationMapId"
						  left join "DoctorSpecializationChargeModuleCategory" DSCC on DSCC."DoctorSpecializationChargeModuleCategoryId" = 																			DSCD."DoctorSpecializationChargeModuleCategoryId"
						 left  join "ChargeModuleTemplate" CMT on CMT."ChargeModuleTemplateId" = DSCC."ChargeModuleTemplateId"
                         left  JOIN "Provider" pr2 on pr2."ProviderId" = LSM."ProviderId" and pr2."Active" is true
						   join "Account" pa on pa."ReferenceId" = pr2."ProviderId" and pa."Active" is true and pa."RoleId" = 3
						  left JOin "LocationAccountMap" LAM on LAM."AccountId" = pa."AccountId" and LAM."Active" IS TRUE
						   join "Specialization" s on s."SpecializationId" = ANY (pr2."Specializations")
                           JOIN "Location" pral on pral."LocationId" = CMT."LocationId" AND pral."Active" IS TRUE
                           JOIN "Practice" pra on pra."PracticeId" = pral."PracticeId" AND pra."Active" IS TRUE
						   JOIN "Department" d on d."DepartmentId" = pr2."DepartmentId" 
						   where pr2."Active" is true and CMT."LocationId" = "locationId"  and s."Active" = true and prl."Active" is true
						   --and CMT."StartDate"::date <= "appointmentDate"::date and CMT."EndDate"::date >= "appointmentDate"::date 
						   and "IsInUse" is true
 
and case when "filter" is null then 1=1 else  TRIM(UPPER(pr2."FullName")) ilike'%'|| "filter"||'%' OR  TRIM(UPPER(s."SpecializationName")) ilike'%'|| "filter"||'%' end 
and case when "consultationTypeId" is null then 1=1 else  prl."ConsultationTypeId" = "consultationTypeId" end
and case when "appointmentDate" is null then CMT."StartDate"::date <= current_date::date and CMT."EndDate"::date >= current_date::date else CMT."StartDate"::date <= "appointmentDate"::date and CMT."EndDate"::date >= "appointmentDate"::date end
	
	--and	case when "locationId" is null then 1=1 else  LAM."LocationId"  = "LocationId" end
	--order by "FullName" asc
;
END
$BODY$;

ALTER FUNCTION public."udf_FetchDoctor_With_Availability_Specialization_Op"(character varying, integer, integer, character varying)
    OWNER TO postgres;

-----------------------------Shravani 29 jun--------------------------------------------------------------------



alter table IF EXISTS "BookScanAppointment" 
add column IF NOT EXISTS "ScanAppointmentType" text default 'OP';
alter table IF EXISTS "BookScanAppointment" 
add column IF NOT EXISTS "PndtReport" boolean;
alter table IF EXISTS "BookScanAppointment" 
add column IF NOT EXISTS "ScanScrollResult" integer;
alter table IF EXISTS "BookScanAppointment" 
drop  constraint if exists "FK_BookScanAppointment_ScanScrollResult";
alter table IF EXISTS "BookScanAppointment" 
add CONSTRAINT "FK_BookScanAppointment_ScanScrollResult" FOREIGN KEY ("ScanScrollResult")
        REFERENCES "LookupValue" ("LookupValueId") MATCH SIMPLE
        ON UPDATE CASCADE
        ON DELETE CASCADE;

INSERT INTO public."Lookup"("Name", "Description")
SELECT 'ScanScrollResult','Scan scroll result'
WHERE
NOT EXISTS (
SELECT "LookupId" FROM public."Lookup" WHERE  "Name" = 'ScanScrollResult'
);

INSERT INTO public."LookupValue"("LookupId", "Name", "CreatedDate", "CreatedBy")
SELECT (select "LookupId" from "Lookup"  where "Name" = 'ScanScrollResult'),'Normal',now(),1029
WHERE
NOT EXISTS (
SELECT "LookupValueId" FROM public."LookupValue" WHERE "LookupId" = (select "LookupId" from "Lookup"  where "Name" = 'ScanScrollResult') and "Name" = 'Normal'
);
INSERT INTO public."LookupValue"("LookupId", "Name", "CreatedDate", "CreatedBy")
SELECT (select "LookupId" from "Lookup"  where "Name" = 'ScanScrollResult'),'Abnormal',now(),1029
WHERE
NOT EXISTS (
SELECT "LookupValueId" FROM public."LookupValue" WHERE "LookupId" = (select "LookupId" from "Lookup"  where "Name" = 'ScanScrollResult') and "Name" = 'Abnormal'
);
INSERT INTO public."LookupValue"("LookupId", "Name", "CreatedDate", "CreatedBy")
SELECT (select "LookupId" from "Lookup"  where "Name" = 'ScanScrollResult'),'Others',now(),1029
WHERE
NOT EXISTS (
SELECT "LookupValueId" FROM public."LookupValue" WHERE "LookupId" = (select "LookupId" from "Lookup"  where "Name" = 'ScanScrollResult') and "Name" = 'Others'
);

-----------------------------Sai pavan 29 jun--------------------------------------------------------------------

alter table IF EXISTS "Location" 
add column IF NOT EXISTS "MapUrl" text ;


alter table IF EXISTS "BookScanAppointment" 
add column IF NOT EXISTS "ActualAmount" numeric;


-- FUNCTION: public.udf_FetchPatients_For_AppointmentScheduleFollowUp(character varying, character varying, character varying, character varying, integer)

-- DROP FUNCTION public."udf_FetchPatients_For_AppointmentScheduleFollowUp"(character varying, character varying, character varying, character varying, integer);
DROP FUNCTION IF EXISTS public."udf_FetchPatients_For_AppointmentScheduleFollowUp"(character varying, character varying, character varying, character varying, integer);
CREATE OR REPLACE FUNCTION public."udf_FetchPatients_For_AppointmentScheduleFollowUp"(
	filter character varying DEFAULT NULL::text,
	"patientMobile" character varying DEFAULT NULL::text,
	"patientName" character varying DEFAULT NULL::text,
	"urlLink" character varying DEFAULT NULL::text,
	"appointmentId" integer DEFAULT NULL::integer)
    RETURNS TABLE("IdProofName" character varying, "RelativeName" character varying, "Relation" character varying, "EducationName" text, "HowDidYouKnow" text, "OccupationName" text, "PatientId" integer, "Salutation" character varying, "FirstName" text, "MiddleName" text, "LastName" text, "FullName" text, "DateOfBirth" date, "Age" smallint, "Gender" character, "MaritalStatus" character, "UMRNo" character varying, "Email" character varying, "Mobile" character varying, "StreetAddress" character varying, "Area" character varying, "City" character varying, "State" character varying, "Zipcode" character varying, "CountryId" integer, "ProfileImageUrl" text, "ThumbnailUrl" text, "Active" boolean, "CreatedBy" integer, "CreatedDate" timestamp without time zone, "ModifiedBy" integer, "ModifiedDate" timestamp without time zone, "Guid" uuid, "ReferralBy" integer, "ReferralCode" character varying, "AadharNo" character varying, "ReferredBy" character varying, "ReferredByName" character varying, "FatherOrHusband" text, "HWCPatientId" integer, "Education" character varying, "Occupation" character varying, "Religion" character varying, "Nationality" character varying, "PatientReferredById" integer, "IdProofValue" character varying, "IdProofId" integer, "BloodGroup" character varying, "Amount" numeric, "PaymentStatus" boolean, "TempPatient" boolean, "HowDidYouKnowId" integer, "EducationId" integer, "OccupationId" integer, "BirthMark1" text, "BirthMark2" text, "RelationType" text, "OccupationDetail" text, "IsNewPatient" boolean, "REGID" character varying, "REGNO" character varying, "InsuranceCompanyId" integer, "ProviderId" integer, "AppointmentId" integer, "PatientType" character, "AppointmentNo" character varying, "AppointmentTime" time without time zone, "AppointmentEndTime" time without time zone, "AppointmentNotes" character varying, "CouponId" integer, "AppointmentAmount" numeric, "Discount" numeric, "Total" numeric, "Status" character, "PatientFamilyId" integer, "DepartmentId" integer, "PaymentType" character, "PaymentNumber" character varying, "AppointmentPaymentStatus" boolean, "VisitTypeId" integer, "ChargeTypesId" integer, "LocationId" integer, "AppointmentTypeId" integer, "PayTypeId" integer, "TokenNumber" integer, "SpecializationId" integer, "ProviderAvailabilityId" integer, "ConsultationTypeId" integer, "DoctorSpecializationChargeModuleDetailsId" integer, "OtherRemarks" character varying, "AuthorityMasterId" integer, "ReasonsId" integer, "Remarks" character varying, "ProviderName" character varying, "ModuleName" character varying, "AppointmentDate" timestamp without time zone, "isActiveAppointmentExists" boolean, "HWCName" character varying, "Description" text, "RowColor" text) 
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000

AS $BODY$
BEGIN

return query

with cts as (
select row_number() over(partition by a."PatientId" order by  a."AppointmentId" desc,
						 a."AppointmentDate" desc )"Max" ,a."PatientId",a."AppointmentId" 
	from "Appointment" a
join  "Patient" pat  on  a."PatientId"	=pat."PatientId"
	join "Provider" pr on a."ProviderId" = pr."ProviderId"
where a."Active"=true 	 
	--and	case when "filter" is null then 1=1 else (TRIM(UPPER(pat."FullName")) ILIKE '%' OR pat."UMRNo"  ilike'%'  OR pat."Mobile" ILIKE '%')|| "filter"||'%' end
	and case when "filter" is null then 1=1 else  TRIM(UPPER(pat."FullName")) ilike'%'|| "filter"||'%' OR  TRIM(UPPER(pat."UMRNo")) ilike'%'|| "filter"||'%' OR  TRIM(UPPER(pat."Mobile")) ilike'%'|| "filter"||'%'  end
	and	case when "patientMobile" is null then 1=1 else  pat."Mobile"  ilike'%'|| "patientMobile"||'%' end
	and	case when "patientName" is null then 1=1 else  pat."FullName"  ilike'%'|| "patientName"||'%' end
	and case when "appointmentId" is null then 1=1 else a."AppointmentId" = "appointmentId" end
)
, maxapt as (
select a.* from "Appointment" a
join cts on a."AppointmentId"=cts."AppointmentId"
where "Max"=1)

SELECT DISTINCT

id."IdProofName",pf."FullName" as "RelativeName",pf."Relation",
eid."Name" as "EducationName",hid."Name" as "HowDidYouKnow",oid."Name" as "OccupationName",

   pat."PatientId",pat. "Salutation",pat. "FirstName",pat. "MiddleName",pat. "LastName",pat. "FullName",pat. "DateOfBirth",pat. "Age",pat. "Gender",pat. "MaritalStatus",pat. "UMRNo",pat. "Email",pat. "Mobile",pat. "StreetAddress",pat. "AddressLine2" as "Area",pat. "City",pat. "State",pat. "Zipcode",pat. "CountryId"
,(CASE WHEN pat."ProfileImageUrl" IS NOT NULL THEN CONCAT("urlLink",'/', pat."Guid", '/', pat."ProfileImageUrl") ELSE '' END) AS "ProfileImageUrl"
,(CASE WHEN pat."ThumbnailUrl" IS NOT NULL THEN CONCAT("urlLink", '/', pat."Guid", '/', pat."ThumbnailUrl") ELSE '' END) AS "ThumbnailUrl"
,pat. "Active",pat. "CreatedBy",pat. "CreatedDate",pat. "ModifiedBy",pat. "ModifiedDate",pat. "Guid",pat. "ReferralBy",pat. "ReferralCode",pat. "AadharNo",referred."Name" as "ReferredBy",pat. "ReferredByName",pat. "FatherOrHusband",pat. "HWCPatientId",pat. "Education",pat. "Occupation",pat. "Religion",pat. "Nationality",pat. "PatientReferredById",pat. "IdProofValue",pat. "IdProofId",pat. "BloodGroup",pat. "Amount",pat. "PaymentStatus",pat. "TempPatient",pat. "HowDidYouKnowId",pat. "EducationId",pat. "OccupationId",pat. "BirthMark1",pat. "BirthMark2",pat. "RelationType",pat. "OccupationDetail",pat. "IsNewPatient",pat. "REGID",pat. "REGNO",pat. "InsuranceCompanyId",
	
	
	apt."ProviderId",	
	 apt."AppointmentId", 
	 apt."PatientType", 
	 apt."AppointmentNo"
	 ,apt."AppointmentTime"
	 ,apt. "AppointmentEndTime"
	 ,apt. "AppointmentNotes",
	 apt."CouponId",
	 apt. "Amount" as "AppointmentAmount",
	 apt."Discount"
	 ,apt. "Total"
	 ,apt. "Status"
	 ,apt. "PatientFamilyId"
	 ,apt. "DepartmentId"
	 ,apt. "PaymentType"
	 ,apt. "PaymentNumber"
	 ,apt. "PaymentStatus"
	 , apt."VisitTypeId"
	 , apt."ChargeTypesId"
	 , apt."LocationId"
	 , apt."AppointmentTypeId"
	 , apt."PayTypeId"
	 , apt."TokenNumber"
	 , apt."SpecializationId"
	 , apt."ProviderAvailabilityId"
	 , apt."ConsultationTypeId"
	 , apt."DoctorSpecializationChargeModuleDetailsId"
	 , apt."OtherRemarks"
	 , apt."AuthorityMasterId"
	 , apt."ReasonsId"
	 , apt."Remarks"	 
	 
	,pr."FullName" as "ProviderName",MM."ModuleName"
,(max(apt."AppointmentDate")over(partition by apt."PatientId")::text ||' ' || max(apt."AppointmentTime")over(partition by apt."PatientId",apt."AppointmentDate")::text)::timestamp as "AppointmentDate",
(case when (max(apt."AppointmentDate")over(partition by apt."PatientId")::text ||' ' || max(apt."AppointmentTime")over(partition by apt."PatientId")::text)::timestamp > now() at time zone 'UTC-5:30' then true else false end)"isActiveAppointmentExists"
, HWC."HWCName", HWC."Description", HWC."RowColor"
FROM "Patient" pat  
left join maxapt apt on apt."PatientId" = pat."PatientId" and apt."Status" <> 'C' and apt."Active"=true
left join "Provider" pr on pr."ProviderId" = apt."ProviderId"
left join "HWCPatient"  HWC on HWC."HWCPatientId" = pat."HWCPatientId"
LEFT JOIN "PatientReferredBy" referred ON referred."PatientReferredById" = pat."PatientReferredById"
left join "IdProof" id on id."IdProofId" = pat."IdProofId"
left join "HowDidYouKnow" hid on hid."HowDidYouKnowId" = pat."HowDidYouKnowId"
left join "Education" eid on eid."EducationId" = pat."EducationId"
left join "Occupation" oid on oid."OccupationId" = pat."OccupationId"
left join "PatientFamily" pf on pf."PatientId" = pat."PatientId"
left join "WebNotification" wn on wn."PatientId" = pat."PatientId"
left join "ModulesMaster" MM on MM."ModulesMasterId" = wn."ModulesMasterId"
 WHERE  pat."Active" IS TRUE 
--and	case when "filter" is null then 1=1 else (TRIM(UPPER(pat."FullName")) ILIKE '%' OR pat."UMRNo"  ilike'%'  OR pat."Mobile" ILIKE '%')|| "filter"||'%' end
and case when "filter" is null then 1=1 else  TRIM(UPPER(pat."FullName")) ilike'%'|| "filter"||'%' OR  TRIM(UPPER(pat."UMRNo")) ilike'%'|| "filter"||'%' OR  TRIM(UPPER(pat."Mobile")) ilike'%'|| "filter"||'%'  end
and	case when "patientMobile" is null then 1=1 else  pat."Mobile"  ilike'%'|| "patientMobile"||'%' end
and	case when "patientName" is null then 1=1 else  pat."FullName"  ilike'%'|| "patientName"||'%' end
and case when "appointmentId" is null then 1=1 else apt."AppointmentId" = "appointmentId" end
;

END
$BODY$;

ALTER FUNCTION public."udf_FetchPatients_For_AppointmentScheduleFollowUp"(character varying, character varying, character varying, character varying, integer)
    OWNER TO postgres;


-----------------------------------------Shivani 29-06-2023-------------------------------------------------------------------------------------------------------

alter table IF EXISTS "ObEncounter" 
add COLUMN IF NOT EXISTS "NurseAssessment" text;

-----------------------------------------Mounika 29-06-2023------------------------------------------------------------------------------------------------------
alter table IF EXISTS "PediatricEncounter"
add column IF NOT EXISTS "PatientId" int;



create sequence  IF NOT EXISTS "Denverchart_DenverchartId_seq";
-- Table: public.Denverchart

--DROP TABLE public."Denverchart";

CREATE TABLE IF NOT EXISTS public."Denverchart"
(
  "DenverchartId" integer NOT NULL DEFAULT nextval('"Denverchart_DenverchartId_seq"'::regclass),
    "ItemName" text NOT NULL,
    "DateOfVisit" text NOT NULL,
    "Comments" text, 
	"Active" boolean NOT NULL DEFAULT true,
	 "CreatedBy" integer,
    "CreatedDate" timestamp(6) without time zone NOT NULL,
	CONSTRAINT "Denverchart_pkey" PRIMARY KEY ("DenverchartId"),

    CONSTRAINT "FK_Account_CreatedBy" FOREIGN KEY ("CreatedBy")
        REFERENCES public."Account" ("AccountId") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION
);


----------------------------------------------------------Srilekha 29-06-2023------------------------------------------------------------------------------------

ALTER TABLE IF EXISTS "Patient"
add COLUMN IF NOT EXISTS "REGNO" character varying;
-----------------------------------------------------------Sravani 30-06-2023-----------------------------------------------------------------------------------
alter table if exists "BookScanAppointment"
add column if not exists "Gravida" text,
add column if not exists "PeriodOfGestation" text,
add column if not exists "Obstetric" boolean,
add column if not exists "EDD" Date,
add column if not exists "AccompaniedBy" text, 
add column if not exists "Findings" text,
add column if not exists "Remarks" text,
add column if not exists "Reasons" text, 
add column if not exists "Dispatched" text,
add column if not exists "BabyDetails" text,
add column if not exists "IsDispatched" boolean;

-----------------------------------------------------------------------Radhika 30-06-2023---------------------------------------------------------------------------
alter table IF EXISTS "GynEncounter" 
DROP CONSTRAINT IF EXISTS "GynEncounter_PatientId_fkey";
alter table IF EXISTS "GynEncounter"
add column IF NOT EXISTS "PatientId" integer,
add CONSTRAINT "GynEncounter_PatientId_fkey" FOREIGN KEY ("PatientId")
 REFERENCES public."Patient" ("PatientId") MATCH SIMPLE;



alter table  IF EXISTS "GynEncounter"
add column IF NOT EXISTS "GyneacAdmissionSheet" text;
alter table IF EXISTS "GynEncounter"
add column IF NOT EXISTS "GyneacSurgery" text;
alter table   IF EXISTS "GynEncounter"
add column IF NOT EXISTS  "GyneacDiscargeSummary" text;



